toss / es-toolkit

A modern JavaScript utility library that's 2-3 times faster and up to 97% smaller—a major upgrade to lodash.
https://es-toolkit.slash.page
Other
7.09k stars 326 forks source link

feature: iterator chain / concatenation #771

Open keturn opened 4 weeks ago

keturn commented 4 weeks ago

Python calls it itertools.chain:

chain("ABC", [1, 2, 3]).toArray() === ["A", "B", "C", 1, 2, 3]

Like Array.concat, but lazy, and doesn't need its iterables to be marked with Symbol.isConcatSpreadable.

(does the toolkit not have an Iterator Utilities section yet?)

keturn commented 4 weeks ago

I believe this may be implemented as

function chain(...iterators) {
    return iterators.flatMap(identity);
}

which is succinct, but a bit quirky maybe.

Alternatively,

function* chain(...iterators) {
    for (const iterator of iterators) {
        yield* iterator;
    }
}