Created
May 20, 2022 18:10
-
-
Save jacky810124/61d1058711d3c0f3a179b4cfa38c13c4 to your computer and use it in GitHub Desktop.
Currying 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
const sum = (...args) => { | |
let result = 0; | |
if (!args.length) { | |
return result; | |
} | |
return (...a) => { | |
result = args.reduce((accumulator, item) => accumulator + item, result); | |
if (!a.length) { | |
return result; | |
} | |
return sum(...args, ...a); | |
}; | |
}; | |
console.log(`sum(): ${sum()} // 0`); | |
console.log(`sum(1)(): ${sum(1)()} // 1`); | |
console.log(`sum(1)(1)(): ${sum(1)(1)()} // 2`); | |
console.log(`sum(1, 1)(): ${sum(1, 1)()} // 2`); | |
console.log(`sum(1)(1, 1)(1)(): ${sum(1)(1, 1)(1)()} // 4`); | |
console.log(`sum(1): ${sum(1)} // function`); | |
console.log(`sum(1, 1, ..., 1): ${sum(1, 1, 1, 1)} // function`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment