Last active
July 7, 2021 05:32
-
-
Save SekiT/418368457a09c6d436b662514afbb130 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const genIterator = (iterable) => | |
typeof iterable === 'function' ? iterable() : iterable[Symbol.iterator]() | |
class Stream { | |
constructor(iterable = []) { | |
this._iterable = iterable | |
this._iterator = genIterator(iterable) | |
} | |
next() { return this._iterator.next() } | |
[Symbol.iterator]() { return genIterator(this._iterable) } | |
map(fun) { | |
const iterable = this._iterable | |
return new Stream(function* () { | |
for (let x of genIterator(iterable)) { | |
yield fun(x) | |
} | |
}) | |
} | |
flatMap(fun) { | |
const iterable = this._iterable | |
return new Stream(function* () { | |
for (let x of genIterator(iterable)) { | |
yield* fun(x) | |
} | |
}) | |
} | |
filter(fun) { | |
const iterable = this._iterable | |
return new Stream(function* () { | |
for (let x of genIterator(iterable)) { | |
if (fun(x)) yield x | |
} | |
}) | |
} | |
take(n) { | |
const iterable = this._iterable | |
return new Stream(function* () { | |
const iterator = genIterator(iterable) | |
for (let count = 0; count < n; count++) { | |
const { done, value } = iterator.next() | |
if (done) return value | |
yield value | |
} | |
}) | |
} | |
static iterate(initialValue, fun) { | |
return new Stream(function* () { | |
let value = initialValue | |
while (true) { | |
yield value | |
value = fun(value) | |
} | |
}) | |
} | |
static cycle(iterable) { | |
return new Stream(function* () { | |
while (true) { | |
yield* genIterator(iterable) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment