README
Generator Extensions
Like Reactive Extensions for Generators
Installation
Add the library to your project
npm install --save generator-extensions
Activate the extensions
require('generator-extensions')
Use the synchronous extensions
function* range(a, b) {
for (let i = a; i < b; i++) {
yield i
}
}
const zero = range(10,20)
.flatMap(x => [x, -x])
.map(x => x * 2)
.reduce((a, b) => a + b)
Use the asynchronous extensions
async function* range(a, b) {
for (let i = a; i < b; i++) {
yield i
}
}
const zero = range(10,20)
.flatMap(x => [x, -x])
.map(x => x * 2)
.reduce((a, b) => a + b)
Operators
toArray
Collects the generator into a single array.
➊──➋──➌
.toArray()
[➊, ➋, ➌]
flatMap
The flatMap() method first maps each element using a mapping function, then flattens the result into a new generator.
➊────➋────➌
.flatMap(x => [x, x + 10])
➊─⓫─➋─⓬─➌─⓭
map
The map() method creates a new generator with the results of calling a provided function on every element in the calling generator.
➊────➋────➌
.map(x => x * 2)
➋────➍────➏
entries
The entries() method returns a new generator that contains the key/value pairs for each index in the generator.
➊────➋────➌
.entries()
[0,➊]──[1,➋]──[2,➌]
filter
The filter() method creates a new generator with all elements that pass the test implemented by the provided function.
➊────➋────➌
.filter(x => x < 2)
➊────➋
find
The find() method returns the value of the first element in the provided generator that satisfies the provided testing function.
➊────➋────➌
.find(x => x > 1)
➋
findIndex
The findIndex() method returns the index of the first element in the generator that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
➊────➋────➌
.findIndex(x => === 2)
1
keys
The keys() method returns a new generator that contains the keys for each index in the generator.
➊────➋────➌
.keys()
0────1────2
reduce
The reduce() method executes a reducer function (that you provide) on each element of the generator, resulting in a single output value.
➊────➋────➌
.reduce((a, b) => a + b, 0)
6
some
The some() method tests whether at least one element in the generator passes the test implemented by the provided function. It returns a Boolean value.
➊────➋────➌
.some(x => x > 2)
true
every
The every() method tests whether all elements in the generator pass the test implemented by the provided function. It returns a Boolean value.
➊────➋────➌
.every(x => x > 2)
false
forEach
The forEach() method executes a provided function once for each array element.