Last active
July 24, 2019 21:20
-
-
Save MikeyBurkman/ab6a2b4370504760293447cdd0441907 to your computer and use it in GitHub Desktop.
"Currying" a single object in a one-arg function
This file contains hidden or 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
type Omit<T1, T2> = { [K in Exclude<keyof T1, keyof T2>]: T1[K] }; | |
const curry = <TDeps, TPartialDeps extends Partial<TDeps>, TReturn>( | |
fn: (deps: TDeps) => TReturn, | |
supplied: TPartialDeps | |
): ((newDeps: Omit<TDeps, TPartialDeps>) => TReturn) => { | |
return (deps: Omit<TDeps, TPartialDeps>) => | |
fn({ | |
...supplied, | |
...deps | |
} as any); | |
}; | |
// Example follows | |
type Deps = { | |
x: number; | |
y: string; | |
z: boolean; | |
}; | |
const foo = (deps: Deps): string => JSON.stringify(deps); | |
const curriedFoo = curry(foo, { x: 42, z: false }); // Only apply x and z to the dependencies | |
const result = curriedFoo({ | |
y: 'abc' // Now only need to the call the function with the one remaining arg | |
}); | |
console.log('Curried function call: ', result); // {"x":42,"z":false,"y":"abc"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment