Skip to main content
Module

x/aitertools/mod.ts>takeWhile

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

Takes elements from the beginning of an async iterable as long as a specified condition is met. If the condition is not met, the iterable stops.

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

const iterable = takeWhile(count(0), v => v < 4);
for await (const value of iterable) console.log(value);

The above example will print the following 4 lines:

0
1
2
3

An async predicate function also works. The following example will print the same 4 lines as the previous example:

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

const iterable = takeWhile(count(0), v => Promise.resolve(v < 4));
for await (const value of iterable) console.log(value);

A predicate function can take an index as well as the value.

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

const iterable = takeWhile(count(0, 10), (_, i) => i < 4);
for await (const value of iterable) console.log(value);

The above example will print the following 4 lines:

0
10
20
30

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.

predicate: (value: T, index: number) => boolean | Promise<boolean>

A predicate function to test each source element for a condition; the second parameter of the function represents the index of the source element. It can be either synchronous or asynchronous.

Returns

AsyncIterableIterator<T>

An async iterable that contains elements from the source iterable that occur before the element at which the predicate no longer passes.