Skip to content

Instantly share code, notes, and snippets.

@MJGTwo
Created August 20, 2019 19:00
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 MJGTwo/594c5e97a09c4bba280ec43f88583c59 to your computer and use it in GitHub Desktop.
Save MJGTwo/594c5e97a09c4bba280ec43f88583c59 to your computer and use it in GitHub Desktop.
A TypeScript function that converts aggregating functions into currying functions if they have the same types. Original idea by Jaco Pretorius.
type aggregateFn<T> = (...args: T[]) => T;
interface curryFn<T> extends aggregateFn<T> {
(...args: T[]): curryFn<T>;
}
const curry = <T>(fn: aggregateFn<T>): curryFn<T> => (
...args: any[]
): curryFn<any> | any =>
args.length ? curry(fn.bind.apply(fn, [undefined].concat(args))) : fn();
const adder = (...subNumbers: number[]) => subNumbers.reduce((acc, itm) => acc += itm, 0)
console.log(adder(1,2,3,4,5)) // 15
const curryAdder = curry(adder)
console.log(curryAdder(1)(2)(3)(4)(5)()) // 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment