Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tdreyno
Last active January 9, 2020 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdreyno/40588715655ca68978f1a9a4b60d68e8 to your computer and use it in GitHub Desktop.
Save tdreyno/40588715655ca68978f1a9a4b60d68e8 to your computer and use it in GitHub Desktop.
Helper method to make `reduce(to(` be a somewhat awkard way to transform arrays to other types.
export function to<A, T>(fn: (items: A[]) => T) {
return (sum: any, _item: A, index: number, all: A[]): T => {
const isLast = index === all.length - 1;
if (!isLast) {
return sum;
}
return fn(all);
};
}
// Example
function join(items: string[]): string {
return items.join('-');
}
['a', 'b', 'c'].reduce(to(join)); // 'a-b-c'
// Or, on the prototype
Array.prototype.chain = <T>(fn: (items: A[]) => T) {
return this.reduce(to(fn));
}
['a', 'b', 'c'].chain(join); // 'a-b-c'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment