Created
May 23, 2018 19:57
-
-
Save kentcdodds/e8d9923e67ccdc558ff8c4076a48aa9d to your computer and use it in GitHub Desktop.
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
// finished version of https://youtu.be/yIcve5wIuAg | |
function add(...args) { | |
function curriedAdd(...args2) { | |
return add(...args, ...args2) | |
} | |
curriedAdd.value = args.reduce((total, current) => total + current) | |
return curriedAdd | |
} | |
console.assert(add(2, 5, 1).value === 8, 'does not work first case') | |
console.assert(add(2)(5)(1).value === 8, 'does not work for second case') | |
console.log(add(2)(5)(1).value) | |
Why not adding:
Object.defineProperty(curriedAdd, 'value', {
get: () => args.reduce((total, current) => total + current)
});
This would avoid computing reduce many time for nothing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one. I think we can call add function like add(curriedAdd.value, ...args2) from the curriedAdd function. That will reduce the number of operations in reduce function.