Skip to content
/ peek Public

Add a peek function to iterators in TypeScript for Deno.

License

Notifications You must be signed in to change notification settings

eibens/peek

Repository files navigation

peek

peek implements a peeking iterator in TypeScript for Deno.

License Deno doc Deno module Github tag Build Code coverage

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.

This module exports all other modules.

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");

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([...abc].join("") === "abc");

About

Add a peek function to iterators in TypeScript for Deno.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published