peek
peek implements a peeking iterator in TypeScript for Deno.
Motivation
A peeking iterator allows one to look at the next item without taking it. This can be useful if one only wants to consume items while a certain condition is met. For example, a scheduler algorithm that only schedules tasks within a certain time window can use a peeking iterator to check whether the event should be scheduled, otherwise leaving it in the iterator for the next scheduling cycle.
mod.ts
This module exports all other modules.
peeking.ts
The fromIterator
function creates a PeekingIterator
from a normal Iterator
by implementing the peek
function.
import {
fromIterator,
PeekingIterator,
} from "https://deno.land/x/peek/peeking.ts";
const peeking: PeekingIterator = fromIterator(
"abc"[Symbol.iterator](),
);
const preview: number = peeking.peek();
console.assert(preview === "a");
// The item is still in the iterator.
const next = peeking.next();
console.assert(next.value === "a");
The fromIterable
function creates a PeekingIterator
from an Iterable
.
import { fromIterable } from "https://deno.land/x/peek/peeking.ts";
const peeking = fromIterable("abc");
console.assert(typeof peeking.peek === "function");
take_while.ts
The takeWhile
generator function removes items from a PeekingIterator
as
long as the specified condition
is met.
import { fromIterable } from "https://deno.land/x/peek/peeking.ts";
import { takeWhile } from "https://deno.land/x/peek/take_while.ts";
const peeking = fromIterable("abcde");
const abc = takeWhile(peeking, (x) => x !== "d");
console.assert(Array.from(abc).join("") === "abc");