Last active
January 9, 2020 17:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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