Skip to main content
Module

x/aitertools/mod.ts>take

Well-tested utility functions dealing with async iterables
Go to Latest
function take
import { take } from "https://deno.land/x/aitertools@0.4.0/mod.ts";

Takes a specified number of elements from the beginning of an async iterable.

import { take } from "./take.ts";
import { count } from "./infinite.ts";

const iterable = take(count(0, 5), 3);
for await (const value of iterable) {
  console.log(value);
}

The above example will print the following 3 lines:

0
5
10

If the iterable is shorter than the specified number, the whole elements are taken.

import { take } from "./take.ts";

async function* gen() { yield "foo"; yield "bar"; yield "baz"; }
const iterable = take(gen(), 5);
for await (const value of iterable) console.log(value);

The above example will print only 3 elements, because gen() yields only 3 elements:

foo
bar
baz

Type Parameters

T

The type of the elements in the source and the returned async iterable.

Parameters

source: Iterable<T> | AsyncIterable<T>

The async iterable to take elements from. It can be either finite or infinite.

count: number

The number of elements to take.

Returns

AsyncIterableIterator<T>

An async iterable that yields the first count elements from the source iterable.