Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Created May 27, 2024 03:00
Show Gist options
  • Save Phryxia/e54e14e7c3c3a7b5493f13d0b5ef8143 to your computer and use it in GitHub Desktop.
Save Phryxia/e54e14e7c3c3a7b5493f13d0b5ef8143 to your computer and use it in GitHub Desktop.
TypeScript implementation of currying for generalized axis
type Remove<R extends unknown[], I extends number, Out extends unknown[] = [], Count extends unknown[] = []>
= R extends []
? Out
: R extends [infer First, ...infer Rest]
? Count['length'] extends I
? Remove<Rest, I, Out, [...Count, 0]>
: Remove<Rest, I, [...Out, First], [...Count, 0]>
: never
type X = Remove<['a', 'b', 'c'], 1>
function curry<F extends (...args: never[]) => unknown, Index extends number>(f: F, index: Index) {
return (arg: Parameters<F>[Index]) =>
(...args: Remove<Parameters<F>, Index>) =>
f(...[...args.slice(0, index), arg, ...args.slice(index)]) as ReturnType<F>
}
@Phryxia
Copy link
Author

Phryxia commented May 27, 2024

Usage

function multiFunction(x: string, y: number, z: boolean) {
  return z ? x : y
}

curry(multiFunction, 0)('babo')(42, true)
curry(multiFunction, 1)(42)('babo', true)
curry(multiFunction, 2)(true)('babo', 42)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment