UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

89 lines (88 loc) 2.15 kB
import { END, SKIP } from '../types.js'; /** * Iterable2 is a wrapper around Iterable that implements "Iterator Helpers proposal": * https://github.com/tc39/proposal-iterator-helpers * * Iterable2 can be removed after the proposal is widely implemented in Node & browsers. * * @experimental */ export class Iterable2 { it; constructor(it) { this.it = it; } static of(it) { return new Iterable2(it); } static empty() { return new Iterable2([]); } [Symbol.iterator]() { return this.it[Symbol.iterator](); } toArray() { return [...this.it]; } forEach(cb) { let i = 0; for (const v of this.it) { if (cb(v, i++) === END) return; } } some(cb) { // oxlint-disable-next-line unicorn/prefer-array-some return !!this.find(cb); } every(cb) { let i = 0; for (const v of this.it) { const r = cb(v, i++); if (r === END || !r) return false; } return true; } find(cb) { let i = 0; for (const v of this.it) { const r = cb(v, i++); if (r === END) return; if (r) return v; } } filter(cb) { const { it } = this; return new Iterable2({ *[Symbol.iterator]() { let i = 0; for (const v of it) { const r = cb(v, i++); if (r === END) return; if (r) yield v; } }, }); } map(mapper) { const { it } = this; return new Iterable2({ *[Symbol.iterator]() { let i = 0; for (const v of it) { const r = mapper(v, i++); if (r === END) return; if (r === SKIP) continue; yield r; } }, }); } }