Skip to content

Instantly share code, notes, and snippets.

@sjkillen
Created May 22, 2018 15:22
Show Gist options
  • Save sjkillen/ce65472ad5d2e6ddbee478e5a70d5323 to your computer and use it in GitHub Desktop.
Save sjkillen/ce65472ad5d2e6ddbee478e5a70d5323 to your computer and use it in GitHub Desktop.
FP primitive functions for use with iterators and the bind operator
/**
* Bindable method for flattening iterables
* @this {Iterable<T>}
* @param {(item: T) => J | void} mapper
* @returns flattened version of iterable with elements mapped
* if a mapper function was given
*/
export function *flattenAll(mapper = v => v) {
for (const item of this) {
if (typeof item === "object" && Symbol.iterator in item) {
yield *flatten.call(item, mapper);
} else {
yield mapper(item);
}
}
}
/**
* Bindable method for flattening iterables a single level
* @this {Iterable<T>}
* @param {(item: T) => J | void} mapper
* @returns flattened version of iterable with elements mapped
* if a mapper function was given
*/
export function *flatten(mapper = v => v) {
for (const item of this) {
if (typeof item === "object" && Symbol.iterator in item) {
yield *map.call(item, mapper);
} else {
yield mapper(item);
}
}
}
/**
* Bindable method for mapping iterables
* @this {Iterable<T>}
* @param {(item: T) => J} mapper
* @returns each item mapped with mapper
*/
export function *map(mapper) {
for (const item of this) {
yield mapper(item);
}
}
/**
* Bindable method for filtering iterables
* @this {Iterable<T>}
* @param {(item: T) => boolean} check
* @returns only items that passed check
*/
export function *filter(check) {
for (const item of this) {
if (check(item)) {
yield item;
}
}
}
/**
* Bindable method for reducing iterables
* @this {Iterable<T>}
* @param {(reduction: R, item: T) => R} reducer
* @returns Reduced value
*/
export function *reduce(reducer) {
let reduction;
for (const item of this) {
reduction = reducer(reduction, item);
}
yield reduction;
}
/**
* Bindable method to convert iterable into scalar value
* Only a single element is taken and returned from iterable
* @this {Iterable<T>}
* @returns next value from iterable
*/
export function single() {
return this[Symbol.iterator]().next().value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment