Methods
(static) array(x) → {array}
- Source:
Transforms an iterable into an array.
This is just a nice functional wrapper for [...iterable], but since everything else is
functions, it looks nicer to have this be a function too. It's mostly for turning the
iterators that this module tends to provide into arrays, but it will work on any kind of
value under the same rules as iterate.
This function will always turn the input into an array. For a function that will turn
inputs also into strings or objects as appropriate, see
collect
const iter = array (iterate ([1, 2, 3, 4, 5]))
const str = array ('test')
const obj = array ({a: 1, b: 2})
const fn = array (x => (x < 5 ? x : undefined))
const single = array (4)
console.log(iter) // [1, 2, 3, 4, 5]
console.log(str) // ["t", "e", "s", "t"]
console.log(obj) // [["a", 1], ["b", 2]]
console.log(fn) // [0, 1, 2, 3, 4]
console.log(single) // [4]
Parameters:
| Name | Type | Description |
|---|---|---|
x |
* | The object which is being made into an array. |
Returns:
An array version of the argument.
- Type
- array
(static) collect(x) → {array|object|string}
- Source:
Collects the elements of an iterable into a JavaScript collection of some kind.
This function is primarily for turning the iterators that are commonly returned by various functions in this module into appropriate concrete collections. Working with iterators all the way through is ideal, but at the end it's usual to need a concrete collection to return.
The kind of output collection depends on the type of input. If the input is a string or a collection of strings, the output will be a string. If the input is an object or a collection of two-element arrays, the output will be an object. Otherwise the output will be an array.
This does create the edge case of, for example, an iterator of two-element arrays that
you actually want to be an array. In that case, use
array instead.
collect is not lazy. By its nature, it must evaluate an entire iterator to work and
is thus not suitable for infinite iterators.
const arr = collect([1, 2, 3, 4, 5])
const str = collect('testing')
const obj = collect({ a: 1, b: 2, c: 3 })
const a2s = collect(['more', ' ', 't', 'est', 'i', 'n', 'g'])
const a2o = collect([[d, 4], [e, 5], [f, 6]])
console.log(arr) // [1, 2, 3, 4, 5]
console.log(str) // "testing"
console.log(obj) // { a: 1, b: 2, c: 3 }
console.log(a2s) // "more testing"
console.log(a2o) // { d: 4, e: 5, f: 6 }
Parameters:
| Name | Type | Description |
|---|---|---|
x |
* | The input collection. This will be transformed into an iterator, so |
Returns:
An output collection (not an iterator) depending on the values in the input collection. If all input elements are strings, this will be a string. If all input elements are two-element arrays, this will be an object. Otherwise this will be an array.
- Type
- array | object | string
(generator, static) concat(x, y) → {iterator}
- Source:
Concatenates two collections. The result is an iterator that first yields elements of the first collection, and when that is finished, the elements over the second collection.
This function works fine with infinite iterators, but be aware that if the first collection is an infinite iterator, the second collection will never be iterated over.
const arrarr = concat ([1, 2, 3]) ([4, 5, 6])
const arrstr = concat ([1, 2, 3]) ('test')
const strstr = concat ('test') ('ing')
console.log(collect(arrarr)) // [1, 2, 3, 4, 5, 6]
console.log(collect(arrstr)) // [1, 2, 3, 't', 'e', 's', 't']
console.log(collect(strstr)) // "testing"
Parameters:
| Name | Type | Description |
|---|---|---|
x |
* | The first collection to be concatenated. |
y |
* | The second collection to be concatenated. |
Returns:
An iterator of all of the elements of x followed by all of the
elements of y.
- Type
- iterator
(generator, static) count(startopt, stepopt) → {iterator}
- Source:
Creates an infinite iterator that counts from a starting point.
By default, the iterator starts at 0 and increases by 1 each invocation. Both of these
can be changed; the first argument is the starting value, and the second is the step
value.
This function can count backwards by choosing a negative step, and it can create an
infinite series of the same number by choosing a step of 0.
This is much like range except that it doesn't have an
end or inclusive parameter and therefore does not, in fact, end. It can also be emulated
by passing a function to iterate that never returns
undefined. The iterate way allows more flexibility - it can emulate any series, not
just a linear one - but infinite is more convenient for the most usual cases.
const iter = count()
console.log(iter.next().value) // 0
console.log(iter.next().value) // 1
console.log(iter.next().value) // 2
...
console.log(iter.next().value) // 42
console.log(iter.next().value) // 43
...
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
start |
number |
<optional> |
0
|
The beginning value for the iterator. |
step |
number |
<optional> |
1
|
The number added to the current value for the next value. |
Returns:
An infinite iterator starting at start and increasing by step on
each iteration.
- Type
- iterator
(generator, static) cycle(x) → {iterator}
- Source:
Produces an iterator that cycles through the values in the input collection infinitely.
Like count, this function can't do anything that
iterate can't already do. However, it can do it more
easily.
const iter = cycle([1, 2, 3])
console.log(iter.next().value) // 1
console.log(iter.next().value) // 2
console.log(iter.next().value) // 3
console.log(iter.next().value) // 1
console.log(iter.next().value) // 2
// The same function, but using iterate
const iter2 = iterate(x => (1 + x % 3))
Notably, cycle can take a single value and repeat that value ad infinitum. This can be
done by iterate or by count, but again cycle does it more easily.
const iter = cycle(3)
console.log(iter.next().value) // 3
console.log(iter.next().value) // 3
console.log(iter.next().value) // 3
console.log(iter.next().value) // 3
console.log(iter.next().value) // 3
// The same function, but using count
const iter2 = count(3, 0)
// And again the same, but with iterate this time
const iter3 = iterate(_ => 3)
Important note: This function internally calls iterate on its argument as many
times as it needed and then produces its values from those iterators. This means you
should not call cycle with a generator argument, as once exhausted, the generator
will no longer yield anything and the function will hang. Use a generator function
instead.
Parameters:
| Name | Type | Description |
|---|---|---|
x |
* | The collection to cycle through infinitely. |
Returns:
An iterator that yields the elements of the input collection over and over, infinitely.
- Type
- iterator
(generator, static) drop(n, x) → {iterator}
- Source:
Returns the collection, minus its first n elements.
If there are fewer than n elements in the collection, an empty iterator will be
returned instead..
const arr = drop(3)([1, 2, 3, 4, 5])
const str = drop(3)('testing')
const obj = drop(3)({ a: 1, b: 2, c: 3, d: 4, e: 5 })
console.log(collect(arr)) // [4, 5]
console.log(collect(str)) // 'ting'
console.log(collect(obj)) // { d: 4, e: 5 }
Parameters:
| Name | Type | Description |
|---|---|---|
n |
number | The number of elements to drop from the input collection. |
x |
iterable | The collection to drop elements from. |
Returns:
An iterator of the elements of x after the first n of them.
- Type
- iterator
(generator, static) dropWhile(fn, x) → {iterator}
- Source:
Drops elements of a collection for as long as a predicate returns true.
The change from dropping elements to yielding them happens once. After dropping stops,
even elements that do not make the predicate return true are yielded.
const result = dropWhile (swap (lt) (3)) ([1, 2, 3, 1, 0])
console.log(result) // [3, 1, 0]
Parameters:
| Name | Type | Description |
|---|---|---|
fn |
function | A function of one parameter that returns a boolean (a predicate).
Elements of the input are passed into the predicate and are yielded by the result
iterator starting when the first one returns |
x |
* | The collection to take elements from. |
Returns:
An iterator that yields elements of x after (and including) the
first one that makes fn return true.
- Type
- iterator
(generator, static) enumerate(x, startopt) → {iterator}
- Source:
Generates a set of pairs of iterable elements with their indices. This is inspired by
Python's enumerate function.
For arrays, these two statements do the same thing:
for (const [i, value] of array.entries()) { ... }for (const [i, value] of enumerate(array)) { ... }
The difference is that enumerate works on any iterable, not only those that have
entries defined upon them.
This function also provides the option to start the index (the first element of the
yielded tuple) from a number other than 0. This number can be passed in as the optional
start parameter.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
x |
iterable | The collection to be enumerated. |
||
start |
number |
<optional> |
0
|
The index of the first tuple that gets yielded. Every succeeding tuple has its index incremented by 1. |
Returns:
An iterator containing one entry for each element in x. Each entry
will be a two-element array of the index followed by the value.
- Type
- iterator
(generator, static) filter(fn, x) → {iterator}
- Source:
Filters the elements of an iterable, returning in an iterator only the ones that make a
filtering function return true.
// Filter odd numbers
const odd = pipe (swap (rem) (2)) (ne (0))
const result = filter (odd) ([1, 2, 3, 4, 5])
console.log(result.next().value) // 1
console.log(result.next().value) // 3
console.log(result.next().value) // 5
console.log(result.next().done) // true
Parameters:
| Name | Type | Description |
|---|---|---|
fn |
function | A predicate function (a single-parameter function that returns a
boolean). This predicate is run once for every element of |
x |
* | The collection to filter. |
Returns:
An iterator containing each element in x that makes fn return
true when applied to it.
- Type
- iterator
(static) iterate(x) → {iterator}
- Source:
Creates an iterator over the provided value.
For values that implement the iterable protocol (i.e., that have properties named
Symbol.iterator that evaluate to functions), It's as simple as that. Therefore, arrays,
strings, and any custom objects that implement the iterable protocol work right out of
the box.
const iter = iterate([1, 2, 3]);
console.log(iter.next().value) // 1
console.log(iter.next().value) // 2
console.log(iter.next().value) // 3
console.log(iter.next().done) // true
Generic objects get special support. If an object (meaning an object literal or something
created with Object.create(), but not custom classes, which have to implement the
iterable protocol explicitly) is passed to iterate, a new iterator will be returned
that iterates over everything that Object.keys returns for that object This will come
out in the "natural" property order, as follows:
- Integer indices, in numerical order. (This does include strings that convert to
integers, such as
'2', but not strings that do not directly correspond to an integer even if they are convertible to integers, such as'02'.) - String property names, in the order in which they were added to the object.
Symbol-keyed properties are not included by this iterator as symbols are intended to be
used for non-enumerable information (neither Object.keys, Object.entries, or
for...in loops include them either, even if they're made enumerable).
The values that this iterator provides are two-element arrays, in which the first element is the key and the second is the value.
const iter = iterate({ b: 2, a: 4 });
console.log(iter.next().value) // ['b',2]
console.log(iter.next().value) // ['a',4]
console.log(iter.next().done) // true
This does not modify the object itself, so it's not actually made "iterable" in any other sense. It's explicit support for objects in this context and nothing more.
If this function is provided a function as its first argument, an iterator is returned
which runs that function one time for each call to next. That function is provided two
arguments: the index of the call (starting at 0 for the first time it's called and
increasing by 1 per invocation after that) and the return value of the previous call to
the function (starting at undefined for the first run before the function is ever
called). If the function ever returns undefined, the iterator will terminate and set
the done property of its return value to true at that point.
Note that since the initial value of the second argument is undefined, using default
arguments is an excellent way of providing the function an initial value.
const constIter = iterate(() => 6) // Bert's favorite number
console.log(constIter.next().value) // 6
console.log(constIter.next().value) // 6
// This will go on forever, as long as `next` keeps getting called
const indexIter = iterate(x => x * x)
console.log(indexIter.next().value) // 0
console.log(indexIter.next().value) // 1
console.log(indexIter.next().value) // 4
console.log(indexIter.next().value) // 9
// Again, this will go on forever, or until the numbers get to big JS to handle
// Using default value on `last` parameter for initial value
const lastIter = iterate((index, last = 1) => last * (index + 1)) // Factorial
console.log(lastIter.next().value) // 1
console.log(lastIter.next().value) // 2
console.log(lastIter.next().value) // 6
console.log(lastIter.next().value) // 24
// Again, forever, though factorials get big quickly
// This iterator will terminate when the function returns `undefined`
const stopIter = iterate(x => x < 2 ? x : undefined)
console.log(stopIter.next().value) // 0
console.log(stopIter.next().value) // 1
console.log(stopIter.next().done) // true
Finally, iterate behaves nicely with generator functions (and with generators
themselves) but there are some things to be aware of.
Passing in a generator function (anything actually defined with function*) will return
a generator, meaning that iterate will invoke the generator function each time it's
called. However, passing in a generator will result in the generator itself (because
generators implement the iterable protocol but simply use it to return themselves).
While both will work, this does mean that passing in the same generator function
multiple times is fine, but passing in the same generator multiple times is probably
not. This is because a generator is an iterator, especially in the sense that after its
traversed, it's useless. Using a generator and then calling iterate with it again will
just return the same spent generator. Calling iterate with a generator function will
return a new generator, ready to be traversed from the beginning. The difference can be
tricky to grasp, but it's important.
Passing in either a generator is fine if it's only being used once.
If the argument is none of these things, then an iterator is returned that yields that argument one time before completing.
Parameters:
| Name | Type | Description |
|---|---|---|
x |
* | The value to be iterated over. |
Returns:
An iterator over the provided value. If the value is not iterable (it's not an object or a function, and it doesn't have a protocol-defined iterator), an iterator that returns only that value once is returned.
- Type
- iterator
(generator, static) map(fn, x) → {iterator}
- Source:
Passes each element of an iterable to a mapping function, returning the results in an iterator.
const result = map (add(1)) ([1, 2, 3])
console.log(result.next().value) // 2
console.log(result.next().value) // 3
console.log(result.next().value) // 4
console.log(result.next().done) // true
Parameters:
| Name | Type | Description |
|---|---|---|
fn |
function | A one-parameter function. Each element of |
x |
* | The collection to map. |
Returns:
An iterator containing the return values of fn when applied to each
of the elements of x.
- Type
- iterator
(generator, static) range(startopt, end, stepopt, inclusiveopt) → {iterator}
- Source:
Generates a range of numbers. This is inspired by Python's range function.
This generator yields a range of numbers, starting with start and incrementing each
succeeding number by step until end is reached. If inclusive is true, then end
itself can be included in the range.
If only one numeric parameter is provided, it is assumed to be end. Two numbers are
interpreted as start and end. In any cases where they aren't specified, start is
0 and step is 1.
If start is greater than end, the range will run in reverse. In this case, each
successive number is decremented by step. step itself should always be positive; if
a negative step is provided, its absolute value will be used instead, and if 0 is
provided, it will be regarded as 1. The direction of the iteration is always determined
by start and end.
// Using collect to change iterators to arrays for ease of display
const e = collect(range(4))
console.log(e) // [0,1,2,3]
const ei = collect(range(4, true))
console.log(ei) // [0,1,2,3,4]
const se = collect(range(2, 4))
console.log(se) // [2,3]
// 0 is necessary because range(4, 2) would be interpreted as a
// start of 4 and end of 2, producing [4,3]
const sep = collect(range(0, 4, 2))
console.log(sep) // [0,2]
const sepi = collect(range(0, 4, 2, true))
console.log(sepi) // [0,2,4]
// Probably the most common use: in `for...of` loops
const a = [0, 1, 2, 3]
const b = [0, 5, 10, 15]
const c = []
// reversed; range produces 3, 2, 1, 0
for (const i of range(3, 0, true)) {
c.push(a[i] * b[i])
}
console.log(c) // [45,20,5,0]
// Sometimes you just need a loop to run x times without caring
// about the index; suggest using _ in that case
function line(length) {
let result = ''
for (const _ of range(length)) result += '-'
return result
}
console.log(line(10)) // "----------"
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
start |
number |
<optional> |
0
|
The first number of the range. |
end |
number | The last number of the range. By default this number forms the upper bound of the range without being included in it. |
||
step |
number |
<optional> |
1
|
The number to increase the yielded value by during each iteration. |
inclusive |
boolean |
<optional> |
false
|
Determines whether |
Returns:
An iterator of numbers that make up the range, according to all of the parameters above.
- Type
- iterator
(static) reduce(fn, x) → {*}
- Source:
Reduces an iterable with a function.
This function will apply the reducer function fn to the first two elements of the input
iterable, and then will apply the same reducer function to that result and the next
element of the iterable, repeating until there are no elements left. The result is a
single answer, which is returned.
reduce is not lazy. By its nature, it must evaluate an entire iterator to work and
is thus not suitable for infinite iterators.
Use of this function is done a little differently than traditional Array.reduce. It
does not have the option of an initial value. This means two things: first, the reduction
of a single-element iterable will just be that single element itself, and second, the
reducer function needs to have both arguments and the return value be of the same type.
This is contrary to Array.reduce, which has a first argument and return value of the
same type but which can take a different type for the second argument.
The upshot is that using a map before the reduce is suggested in many scenarios
where, in traditional JavaScript reduction, you would do that mapping as a part of the
reducer function itself. For example, if one wanted to turn an array of digits into
strings and then concatenate them, the Array.reduce way would be like this:
const fn = (acc, value) => acc + value.toString()
function stringify(xs) {
return xs.reduce(fn, '')
}
This maps the values in the middle of the reducer function (the toString call) and
wouldn't work as well with this iterator reduce. Instead, you would want to do this:
function stringify(xs) {
const mapped = map(x => x.toString(), xs)
return reduce((x, y) => x + y, mapped)
}
Though in reality, with the other functions in this library, it would be even better to do this:
const stringify = compose (reduce (add), map (string))
Requiring the reducer function to take two arguments of the same type makes you have to think more about the kind of reduction you want to do, but it makes it easier to use functions you already have lying around to do things in a more concise and understandable manner.
Parameters:
| Name | Type | Description |
|---|---|---|
fn |
function | The reducer function, a function of two parameters that will receive the current value and the next element as arguments. |
x |
* | The collection to reduce. This can be of any type; a non-iterable value will be transformed into an array containing only that value. |
Returns:
The result of the reducer function's last call.
- Type
- *
(generator, static) reverse(x) → {iterator}
- Source:
Reverses the order of an iterable.
reverse should not be used with infinite iterators. By its nature, it must evaluate
an entire iterator so that it can find the end, which is where the new iterator will
begin. Thus it returns a lazy value (an iterator), but it eagerly evaluates its input.
const arr = reverse ([1, 2, 3, 4, 5])
const str = reverse ('test')
const fn = reverse (x => (x < 5 ? x : undefined))
console.log(arr) // [5, 4, 3, 2, 1]
console.log(str) // ["t", "s", "e", "t"]
console.log(fn) // [4, 3, 2, 1, 0]
Parameters:
| Name | Type | Description |
|---|---|---|
x |
* | The collection to reverse. |
Returns:
An iterator over a version of x with its elements in reverse order.
- Type
- iterator
(generator, static) scan(fn, x) → {iterator}
- Source:
Reduces an iterable with a function, returning an iterator with all of the intermediate results.
This acts very much like reduce, except instead of returning the final answer, it
returns the intermediate values from each time the function is run (in an iterator). The
first value is prepended unmodified to the iterator; this is to ensure that the length of
the result of scan is the same as the length of the input.
Use of this function is done a little differently than traditional Array.reduce. It
does not have the option of an initial value. The first calculated value is just the
result of the reducer function fn applied to the first two elements of the input. This
means that the reduction function needs to be able to handle both an input element and an
"accumulator" as its first argument.
Because the initial value in the result iterator will not be passed through the reducer
function, it's often best to use map before scan rather than depend on the reducer
function to do its own mapping, as is often done in JavaScript. For instance, if a
reducer function makes characters uppercase, it will still not affect the first value in
the output iterator; that value is never passed through the reducer function. Mapping to
uppercase and then scanning may be better.
Also, since the first invocation of the reducer function is sent two elements rather than
an accumulator value and an element, it's important to be sure that any "mapping" is done
on both arguments. For instance, a scan that is supposed to turn numbers into strings and
then concatenate them will have to be sure that both arguments are turned to strings,
since the first invocation will receive two numbers rather than a string and a number. It
would probably be best to map the numbers to strings first and then concatenate them
with scan after.
scan is a curried function and can therefore easily be partially applied. It accepts a
reducer function that can be curried or uncurried.
const runningSum = scan (add) ([0, 1, 2, 3, 4])
console.log(runningSum.next().value) // 0
console.log(runningSum.next().value) // 1
console.log(runningSum.next().value) // 3
console.log(runningSum.next().value) // 6
console.log(runningSum.next().value) // 10
const mulScan = scan (mul)
const factorial = mulScan ([1, 2, 3, 4, 5])
console.log(factorial.next().value) // 1
console.log(factorial.next().value) // 2
console.log(factorial.next().value) // 6
console.log(factorial.next().value) // 24
console.log(factorial.next().value) // 120
Parameters:
| Name | Type | Description |
|---|---|---|
fn |
function | The reducer function, a function of two parameters that will receive the current value and the next element as arguments. |
x |
* | The collection to scan. This can be of any type; a non-iterable value will be transformed into an array containing only that value. |
Returns:
An iterator containing each of the return values of the reducer
function fn.
- Type
- iterator
(generator, static) take(n, x) → {iterator}
- Source:
Returns the first n elements of a collection.
If there are fewer than n elements in the collection already, the collection will be
returned. No additional elements will be added to it.
const arr = take(3)([1, 2, 3, 4, 5])
const str = take(3)('testing')
const obj = take(3)({ a: 1, b: 2, c: 3, d: 4, e: 5 })
console.log(collect(arr)) // [1, 2, 3]
console.log(collect(str)) // 'tes'
console.log(collect(obj)) // { a: 1, b: 2, c: 3 }
Parameters:
| Name | Type | Description |
|---|---|---|
n |
number | The number of elements to take from the input collection. |
x |
iterable | The collection to take elements from. |
Returns:
An iterator of the first n elements of x.
- Type
- iterator
(generator, static) takeWhile(fn, x) → {iterator}
- Source:
Returns the elements of a collection until a predicate returns false.
The change from returning elements to not happens exactly once. Once the predicate is
false, the return iterator is complete. It will not then test any further elements, so
later elements that make the predicate produce true will not be yielded. (That's the
difference between this function and filter; the latter
will continue to yield elements even after the first one that returns false from the
predicate).
const result = takeWhile (swap (lt) (3)) ([1, 2, 3, 1, 0])
console.log(result) // [1, 2]
Parameters:
| Name | Type | Description |
|---|---|---|
fn |
function | A function of one parameter that returns a boolean (a predicate).
Elements of the input are passed into the predicate and are yielded by the result
iterator until the first one returns |
x |
* | The collection to take elements from. |
Returns:
An iterator that yields elements of x until the first one that
makes fn return true.
- Type
- iterator