Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created May 23, 2018 19:57
Show Gist options
  • Save kentcdodds/e8d9923e67ccdc558ff8c4076a48aa9d to your computer and use it in GitHub Desktop.
Save kentcdodds/e8d9923e67ccdc558ff8c4076a48aa9d to your computer and use it in GitHub Desktop.
// 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)
@avinashsivaraman
Copy link

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.

const add = (...args) => {
    const curriedAdd = (...args1) => {
        return add(curriedAdd.value, ...args1)
    }
    curriedAdd.value = args.reduce((total, current) => total + current)
    return curriedAdd
}

console.log(add(2,3,5,12,-1))
console.log(add(2,3)(5)(8,6)(9))

@mathk
Copy link

mathk commented May 25, 2018

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