Default

import iter from 'iterfn';

Turns an iterable object, iterator object or a generator function into an iterator that is also iterable and adds methods to easily operate on the values. These methods can be chained until a consumer is called.

iter(iterable: (Iterable | Iterator | Generator)): Iterator
Parameters
iterable ((Iterable | Iterator | Generator)) An iterable object, iterator object or generator function that can be turned into an iterator.
Returns
Iterator: An iterable iterator with additional methods to operate on its values.
Throws
  • TypeError: Throws when the input cannot be converted to an iterator.

Adapters

An adapter takes an iterator and returns another iterator.

Takes two or more iterables and creates an iterator over their values in sequence. It will first iterate over the values from the first iterable, then the second and so on.

chain(iters: ...Iterable): Iterator
Parameters
iters (...Iterable) The iterables that will be chained.
Returns
Iterator: A chained iterator.
Example
const a1 = [1, 2];
const a2 = [3, 4];

const iter = chain(a1, a2);

iter.next(); // { value: 1, done: false };
iter.next(); // { value: 2, done: false };
iter.next(); // { value: 3, done: false };
iter.next(); // { value: 4, done: false };
iter.next(); // { value: undefined, done: true };

Repeats an iterable indefinitely. When the iterable is done, it will start again from the beginning.

cycle(iter: Iterable): Iterator
Parameters
iter (Iterable) An iterable to be repeated indefinitely.
Returns
Iterator: An infinite iterator.
Example
const a = [1, 2];

const iter = cycle(a);

iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 1, done: false }
// etc.

Creates an iterator which gives the current index as well as the value. The index starts at 0.

enumerate(iter: Iterable): Iterator
Parameters
iter (Iterable) An iterable to be enumerated.
Returns
Iterator: An iterator which yields pairs of index and value.
Example
const a = ['a', 'b', 'c'];

const iter = enumerate(a);

iter.next(); // { value: [0, 'a'], done: false }
iter.next(); // { value: [1, 'b'], done: false }
iter.next(); // { value: [2, 'c'], done: false }
iter.next(); // { value: undefined, done: true }

Creates an iterator which yields only the values that satisfy the predicate.

filter(iterable: Iterable, filterFunc: Function, iter: any): Iterator
Parameters
iterable (Iterable) An iterable to be filtered.
filterFunc (Function) A function that receives the values of the iterable and returns a boolean. If it returns true, the value is yielded, and if it returns false, it will move to the next value.
iter (any)
Returns
Iterator: An iterator which yields only the values that satisfy the predicate.
Example
const a = [1, 2, 3, 4, 5, 6];
const isEven = x => x % 2 === 0;

const iter = filter(a, isEven);

iter.next(); // { value: 2, done: false }
iter.next(); // { value: 4, done: false }
iter.next(); // { value: 6, done: false }
iter.next(); // { value: undefined, done: true }

Creates an iterator that both filters and maps. When the mapped value is null or undefined, it is skipped, otherwise it will be yielded.

filterMap(iter: Iterable, func: Function): Iterator
Parameters
iter (Iterable) An iterable to be filtered and mapped.
func (Function) A function that receives the values of the iterable and returns a new value. If it returns null or undefined, it will move to the next value, and if it returns any other value, the returned value is yielded.
Returns
Iterator: An iterator which yields the filtered and mapped values.
Example
const a = [1, 2, 3, 4, 5, 6];
const squareOdd = x => {
  if (x % 2 === 0) {
    return null;
  }
  return x * x;
};

const iter = filterMap(a, squareOdd);

iter.next(); // { value: 1, done: false }
iter.next(); // { value: 9, done: false }
iter.next(); // { value: 25, done: false }
iter.next(); // { value: undefined, done: true }

Creates an iterator which works like map, but flattens nested structures. The map function has to return an iterable instead of just a value. Consequently all values of the returned iterables are yielded.

flatMap(iterable: Iterable, mapFunc: Function, iter: any): Iterator
Parameters
iterable (Iterable) An iterable to be mapped and flattened.
mapFunc (Function) A function that returns an iterable for each value. All the values of the returned iterables are yielded.
iter (any)
Returns
Iterator: An iterator which yields all values of the mapped iterables.
Example
function* valNtimes(val, n) {
  for (let i = 0; i < n; i++) {
    yield val;
  }
}
const a = [1, 2, 3];

const iter = flatMap(a, x => valNtimes(x, x));

iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 3, done: false }
iter.next(); // { value: 3, done: false }
iter.next(); // { value: 3, done: false }
iter.next(); // { value: undefined, done: true }
const strings = ['abc', 'xyz'];

// Strings are also iterable and therefore valid return values
const iter = flatMap(strings, s => s);

iter.next(); // { value: 'a', done: false }
iter.next(); // { value: 'b', done: false }
iter.next(); // { value: 'c', done: false }
iter.next(); // { value: 'x', done: false }
iter.next(); // { value: 'y', done: false }
iter.next(); // { value: 'z', done: false }
iter.next(); // { value: undefined, done: true }

Creates an iterator which ends after the first null or undefined value is encountered. An iterator could potentially yield null or undefined before being done and continue yielding more values afterwards.

fuse(iter: Iterable): Iterator
Parameters
iter (Iterable) An iterable to be fused.
Returns
Iterator: A fused iterator.
Example
// Yields even numbers or null
function* alternate() {
 let i = 0;
 while (true) {
   if (i % 2 === 0) {
     yield i;
   } else {
     yield null;
   }
   i += 1;
 }
}

const iter = alternate();

iter.next(); // { value: 0, done: false }
iter.next(); // { value: null, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: null, done: false }
// Would continue indefinitely

const fused = fuse(iter);

fused.next(); // { value: 4, done: false }
// Stops after it encounters null or undefined
fused.next(); // { value: undefined, done: true }

// This also ends the original iterator
iter.next(); // { value: undefined, done: true }

Creates an iterator which calls the given function with each value before passing the value on. When chaining a lot of iterables it might be useful to check out what's happening with the values. This is intended for debugging purposes.

inspect(iter: Iterable, func: Function): Iterator
Parameters
iter (Iterable) An iterable to be inspected.
func (Function) A function that is called with each value.
Returns
Iterator: An iterator which calls a function before passing the value on.
Example
const a = [1, 2, 4, 3];

const sum1 = iter(a)
  .filter(x => x % 2 === 0)
  .fold(0, (sum, i) => sum + i);

// Could be helpful to see what values make it through the chain
// Just add inspect() between the steps
const sum2 = iter(a)
  .inspect(x => console.log(`about to filter: ${x}`))
  .filter(x => x % 2 === 0)
  .inspect(x => console.log(`made it through filter: ${x}`))
  .fold(0, (sum, i) => sum + i);
about to filter: 1
about to filter: 2
made it through filter: 2
about to filter: 4
made it through filter: 4
about to filter: 3

Creates an iterator which transforms each value into a new one.

map(iter: Iterable, mapFunc: Function): Iterator
Parameters
iter (Iterable) An iterable to be mapped.
mapFunc (Function) A function that transforms each value.
Returns
Iterator: An iterator which yields the transformed values.
Example
const a = [1, 2, 3];

const iter = map(a, x => x * 2);

iter.next(); // { value: 2, done: false }
iter.next(); // { value: 4, done: false }
iter.next(); // { value: 6, done: false }
iter.next(); // { value: undefined, done: true }

Creates an iterator which yields the values in reverse order. The given iterable needs to be fully consumed before the values can be yielded in reverse, hence it will result in an infinite loop if it is called on an infinite iterator.

reverse(iter: Iterable): Iterator
Parameters
iter (Iterable) An iterable to be reversed.
Returns
Iterator: A reversed iterator.
Example
const a = [1, 2, 3];

const iter = reverse(a);

iter.next(); // { value: 3, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 1, done: false }
iter.next(); // { value: undefined, done: false }

Creates an iterator which accumulates a value. This is similar to fold or reduce, but instead of creating a single value, it yields each step of the accumulator, making the last value equivalent to the output of fold or reduce.

scan(iter: Iterable, initialValue: Any, func: Function): Iterator
Parameters
iter (Iterable) An iterable to be scanned.
initialValue (Any) The initial value of the accumulator.
func (Function) A function that receives two arguments, the accumulator and the current value, and returns the new accumulated value, which is also yielded.
Returns
Iterator: An iterator which yields each step of the accumulator.
Example
const a = [1, 2, 3];

const iter = scan(a, 1, (acc, x) => acc * x);

iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 6, done: false }
iter.next(); // { value: undefined, done: false }

Creates an iterator that skips the first n values.

skip(iter: Iterable, n: number): Iterator
Parameters
iter (Iterable) An iterable to be skipped ahead.
n (number) The number of values to be skipped.
Returns
Iterator: An iterator which yields every value starting after the first n values.
Example
const a = [1, 2, 3, 4];

const iter = skip(a, 2);

iter.next(); // { value: 3, done: false }
iter.next(); // { value: 4, done: false }
iter.next(); // { value: undefined, done: false }

Creates an iterator which skips values until the predicate becomes false.

skipWhile(iter: Iterable, predicate: Function): Iterator
Parameters
iter (Iterable) An iterable to be skipped ahead.
predicate (Function) A function that receives the values of the iterable and returns a boolean. As long as it returns true, the values will be ignored, and once it returned false, it stops.
Returns
Iterator: An iterator which yields all values after the predicate became false.
Example
const a = [1, 3, 6, 11, 13, 2, 4];

const iter = skipWhile(a, x => x < 10);

iter.next(); // { value: 11, done: false }
iter.next(); // { value: 13, done: false }
// This would be false, but skipWhile already stopped after the first false
iter.next(); // { value: 2, done: false }
iter.next(); // { value: 4, done: false }
iter.next(); // { value: undefined, done: true }

Creates an iterator which yields the first n values of the iterable.

take(iter: Iterable, n: number): Iterator
Parameters
iter (Iterable) An iterable from which n values are taken.
n (number) The number of values to take from the iterable.
Returns
Iterator: An iterator which yields the first n values.
Example
const a = [1, 2, 3];

const iter = take(a, 2);

iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: undefined, done: true }
// Often used for infinite iterators
function* naturalNumbers() {
  let i = 0;
  while (true) {
    yield i;
    i += 1;
  }
}

const iter = take(naturalNumbers(), 3);

iter.next(); // { value: 0, done: false }
iter.next(); // { value: 1, done: false }
iter.next(); // { value: 2, done: false }
iter.next(); // { value: undefined, done: true }

Creates an iterator which yields values while the predicate is true.

takeWhile(iter: Iterable, predicate: Function): Iterator
Parameters
iter (Iterable) An iterable from which values are taken.
predicate (Function) A function that receives the values of the iterable and returns a boolean. As long as it returns true, the values will be yielded, and once it returned false, it stops.
Returns
Iterator: An iterator which yields values while the predicate is true.
Example
const a = [1, 3, 6, 11, 13, 2, 4];

const iter = takeWhile(a, x => x < 10);

iter.next(); // { value: 1, done: false }
iter.next(); // { value: 3, done: false }
iter.next(); // { value: 6, done: false }
iter.next(); // { value: undefined, done: true }
// There are more values below 10 but takeWhile stops after the first false

Creates an iterator which yields a pair of values that correspond to a value from the first and the second iterable, and stops when one of the two iterables is done.

zip(iterable1: Iterable, iterable2: Iterable): Iterator
Parameters
iterable1 (Iterable) An iterable which provides the first value in the pair of values.
iterable2 (Iterable) An iterable which provides the second value in the pair of values.
Returns
Iterator: An iterator which yields a pair of values from the two iterables.
Example
const a1 = [1, 2, 3];
const a2 = [4, 5, 6];

const iter = zip(a1, a2);

iter.next(); // { value: [1, 4], done: false }
iter.next(); // { value: [2, 5], done: false }
iter.next(); // { value: [3, 6], done: false }
iter.next(); // { value: undefined, done: true }
// This can be used to zip an infinite iterator to a finite one
function* naturalNumbers() {
  let i = 0;
  while (true) {
    yield i;
    i += 1;
  }
}
const a = ['a', 'b', 'c'];

const iter = zip(naturalNumbers(), a);

iter.next(); // { value: [0, 'a'], done: false }
iter.next(); // { value: [1, 'b'], done: false }
iter.next(); // { value: [2, 'c'], done: false }
iter.next(); // { value: undefined, done: true }

Consumers

A consumer takes an iterator and consumes it to produce a value. Infinite operators result in an infinite loop, unless the function short-circuits.

Tests if every value of the iterable satisfies the predicate. When all values satisfy the predicate it returns true, otherwise false. Once the predicate returns false for any value, the result will be false no matter what else happens and therefore it stops processing additional values (short-circuiting). An empty iterable returns true.

all(iter: Iterable, predicate: Function): boolean
Parameters
iter (Iterable) An iterable to be tested against the predicate.
predicate (Function) A function that receives the values of the iterable and returns a boolean.
Returns
boolean: Whether all values satisfy the predicate.
Example
const a = [1, 2, 3];

all(a, x => x > 0); // true
all(a, x => x < 2); // false

Tests if any value of the iterable satisfies the predicate. When any value satisfies the predicate it returns true, otherwise false. Once the predicate returns true for any value, the result will be true no matter what else happens and therefore it stops processing additional values (short-circuiting). An empty iterable returns false.

any(iter: Iterable, predicate: Function): boolean
Parameters
iter (Iterable) An iterable to be testes against the predicate.
predicate (Function) A function that receives the values of the iterable and returns a boolean.
Returns
boolean: Whether any value satisfies the predicate.
Example
const a = [1, 2, 3];

any(a, x => x > 0); // true
any(a, x => x > 5); // false

Transforms the iterable into a collection. By default an array is constructed unless a transformation function is supplied.

collect(iter: Iterable, fromIter: Function?): Any
Parameters
iter (Iterable) An iterable to be transformed into a collection.
fromIter (Function? = Array.from) A function that receives the iterable and returns a collection. When no function is given, it uses Array.from to create an Array.
Returns
Any: A collection constructed from the values of the iterable.
Example
function* helloWorld() {
  yield 'hello';
  yield ' ';
  yield 'world';
}

collect(helloWorld()); // ['hello', ' ', 'world']

// Custom function to create a collection out of an iterable
function concatIter(iter) {
  let str = '';
  for (const val of iter) {
    str += val;
  }
  return str;
}
const a = [1, 2, 3, 4];

collect(helloWorld(), concatIter); // 'hello world'
collect(a, concatIter); // '1234'

Consumes an iterable, counting the number of iterations and returning it. As the iterable needs to be fully consumed, it will result in an infinite loop if is is called on an infinite iterator.

count(iter: Iterable): number
Parameters
iter (Iterable) An iterable to be counted.
Returns
number: The number of iterations.
Example
const a = [1, 2, 3, 4, 5];

count(a); // 5

Searches for a value in the iterable that satisfies the predicate. If any of the values satisfies the predicate, the value will be returned, otherwise it returns undefined.

find(iter: Iterable, predicate: Function): (Any | undefined)
Parameters
iter (Iterable) An iterable to search a value in.
predicate (Function) A function that receives the values of the iterable and returns a boolean. When it returns true for a value, the value is returned and all further values are ignored.
Returns
(Any | undefined): The first value which satisfied the predicate or undefined if no value satisfied it.
Example
const a = [1, 2, 3, 4, 5];

find(a, x => x === 4); // 4
find(a, x => x > 4); // 5
find(a, x => x > 10); // undefined

Applies a function to each value, producing a single, final value. This is similar to reduce, except that an initial value needs to be supplied.

fold(iter: Iterable, initialValue: Any, func: Function): Any
Parameters
iter (Iterable) An iterable to be consumed to create a final value.
initialValue (Any) The initial value of the accumulator.
func (Function) A function that receives two arguments, the accumulator and the current iterable value, and returns the new accumulated value.
Returns
Any: The final value of the accumulator.
Example
const a = [1, 2, 3];

const sum = fold(a, 0, (acc, x) => acc + x); // 6
const sumOffset = fold(a, 10, (acc, x) => acc + x); // 16

Applies a function to each value of the iterable and consumes it. This has the same effect as simply using a for-of loop, which should be preferred over this.

forEach(iter: Iterable, func: Function): void
Parameters
iter (Iterable) An iterable to be consumed.
func (Function) A function that is called with each value.
Returns
void:
Example
const a = [1, 2, 3];

forEach(a, console.log);
1
2
3

Joins all values of the iterable into a string separated with the provided separator. This will automatically convert the values to a string. The default separator is ','.

join(iter: Iterable, separator: string?): string
Parameters
iter (Iterable) An iterable whose values are joined.
separator (string? = ',') The separator used between the values.
Returns
string: The joined string.
Example
const customToString = {
  toString() {
    return 'custom toString';
  }
};
const a = ['hello', 99, [1, 2], {}, customToString];

join(a); // 'hello,99,1,2,[object Object],custom toString'
join(a, ' - '); // 'hello - 99 - 1,2 - [object Object] - custom toString'

Consumes an iterable and returns the last value.

last(iter: Iterable): Any
Parameters
iter (Iterable) An iterable to be consumed.
Returns
Any: The last value of the iterable.
Example
const a = [1, 2, 3, 4, 5];

last(a); // 5
last([]); // undefined

Returns the maximum value of an iterable. If two values are equally maximum, the last value is returned.

max(iter: Iterable): Any
Parameters
iter (Iterable) An iterable to find the maximum value.
Returns
Any: The maximum value of the iterable.
Example
const a = [1, 2, 3];

max(a); // 3
max([]); // undefined

Returns the minimum value of an iterable. If two values are equally minimum, the first value is returned.

min(iter: Iterable): Any
Parameters
iter (Iterable) An iterable to find the minimum value.
Returns
Any: The minimum value of the iterable.
Example
const a = [1, 2, 3];

min(a); // 1
min([]); // undefined

Returns the nth value of an iterable. Like most indexing operations, The count starts from zero (i.e. nth(iter, 0) returns the first value). If n is greater than or equal the number of values in the iterable, it returns undefined.

nth(iter: Iterable, n: number): (Any | undefined)
Parameters
iter (Iterable) An iterable to take the nth value from.
n (number) The index of the value.
Returns
(Any | undefined): The nth value or undefined if n is greater than or equal to the number of values in the iterable.
Example
const a = [1, 2, 3];

nth(a, 2); // 2
nth(a, 5); // undefined

Creates two arrays, where the first array contains all values for which the predicate is true and the second contains all values for which it is false.

partition(iter: Iterable, predicate: Function): [Array, Array]
Parameters
iter (Iterable) An iterable to be partitioned.
predicate (Function) A function that receives the values of the iterable and returns a boolean. If it returns true, the value goes into the first array and if it returns false, the value goes into the second array.
Returns
[Array, Array]: An array containing two arrays where the first one contains values for which the predicate is true and the second contains all values for which it is false.
Example
const a = [1, 2, 3, 4, 5];
const isEven = x => x % 2 === 0;

const [even, odd] = partition(a, isEven);
even; // [2, 4]
odd;  // [1, 3, 5]

Searches for a value in the iterable that satisfies the predicate and returns its index. If no value satisfies the predicate, -1 is returned.

position(iter: Iterable, predicate: Function): number
Parameters
iter (Iterable) An iterable to search a value in.
predicate (Function) A function that receives the values of the iterable and returns a boolean. When it returns true for a value, its index is returned and all further values are ignored.
Returns
number: The index of the first value which satisfied the predicate or -1 if no value satisfied it.
Example
const a = [1, 2, 3, 4, 5];

position(a, x => x === 4); // 3
position(a, x => x > 4); // 4
position(a, x => x > 10); // -1

Multiplies all values of the iterable together.

product(iter: Iterable): number
Parameters
iter (Iterable) An iterable whose values are multiplied.
Returns
number: The result of multiplying all values of the iterable.
Example
const a = [1, 2, 3, 4];

product(a); // 24

Applies a function to each value, producing a single, final value. This similar to fold, but uses the first value of the iterable as initial value if no initial value is given and the order of the parameters is swapped to mimic Array.prototype.reduce. Note that the initial value is not run through the function but taken as is.

reduce(iter: Iterable, func: Function, initialValue: Any?): (Any | undefined)
Parameters
iter (Iterable) An iterable to be consumed to create a final value.
func (Function) A function that receives two arguments, the accumulator and the current iterable value, and returns the new accumulated value.
initialValue (Any?) The initial value of the accumulator, when it is not supplied, the first value of the iterable is taken as the initial value instead.
Returns
(Any | undefined): The final value of the accumulator or undefined when no value is available.
Example
const a = [2, 4, 6];

reduce(a, (acc, x) => acc + x); // 12
reduce(a, (acc, x) => acc + x, 10); // 22

// If no initial value is provided, the first value is not built with the
// given function, but simply given as the accumulator to the first call.
reduce(a, (acc, x) => acc + x * 3) // 32
reduce(a, (acc, x) => acc + x * 3, 0) // 36

Sums all values of the iterable.

sum(iter: Iterable): number
Parameters
iter (Iterable) An iterable whose values are added together.
Returns
number: The sum of all values of the iterable.
Example
const a = [1, 2, 3, 4];

sum(a); // 10

Converts an iterable of pairs into two arrays, where each contains the values of the respective position in the pair.

unzip(iter: Iterable): [Array, Array]
Parameters
iter (Iterable) An iterable of pairs to be unzipped.
Returns
[Array, Array]: An array containing two arrays where each contains the values of the respective position in the pair of the iterable.
Example
const a = [[0, 'a'], [1, 'b']];

const [left, right] = unzip(a);
left;  // [0, 1]
right; // ['a', 'b']

Extension

Directly create an extended iterator.

extendIterator

src/index.js

Adds methods that call the respective functions on the iterator which can be chained as long as the functions return another iterator.

extendIterator(iter: Iterator): Iterator
Parameters
iter (Iterator) An iterator that gets extended.
Returns
Iterator: The extended iterator.

iterFromIterable

src/index.js

Turns an iterable object into an iterator and adds methods to easily operate on the values.

iterFromIterable(iterable: Iterable): Iterator
Parameters
iterable (Iterable) An iterable object that can be turned into an iterator.
Returns
Iterator: An iterator with additional methods to operate on its values.

iterFromGenerator

src/index.js

Turns a generator function into an iterator and adds methods to easily operate on the values.

iterFromGenerator(generator: Generator): Iterator
Parameters
generator (Generator) A generator function that return an iterator.
Returns
Iterator: An iterator with additional methods to operate on its values.

iterFromIterator

src/index.js

Turns an iterator object into an iterable iterator and adds methods to easily operate on the values. Usually an iterator is iterable as well, but it is not a requirement.

iterFromIterator(iterator: Iterator): Iterator
Parameters
iterator (Iterator) An iterator object to be turned into an iterable iterator.
Returns
Iterator: An iterator with additional methods to operate on its values.

Utils

Utility functions to determine the potential iterator types.

Required to be imported from lib/utils.

import * as utils from 'iterfn/lib/utils';

isGeneratorFunction

src/utils.js

Checks whether the given object is a generator function.

isGeneratorFunction(obj: Object): boolean
Parameters
obj (Object) An object to be checked.
Returns
boolean: Whether the object is a generator function.

isIterable

src/utils.js

Checks whether the given object is iterable.

isIterable(obj: Object): boolean
Parameters
obj (Object) An object to be checked.
Returns
boolean: Whether the object is iterable.

isIterator

src/utils.js

Checks whether the given object is an iterator.

isIterator(obj: Object): boolean
Parameters
obj (Object) An object to be checked.
Returns
boolean: Whether the object is an iterator.