Last active
May 14, 2022 14:58
-
-
Save ajitid/a3da2c08cadfac8f30974d4fdf63f35d to your computer and use it in GitHub Desktop.
sum(1)(2)(3)() - sum curry recursive like
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
function sum(a) { | |
if(a == null) return 0 | |
return b => b == null ? a : sum(a + b) | |
} | |
/* | |
sum() // 0 | |
sum(1) // 1 | |
sum(1)(2)() // 3 | |
sum(1)(2)(3) // 6 | |
*/ |
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
// my peer ananto pointed out that we can't easily use typescript on these functions | |
function sum(v) { | |
if(v === undefined) { | |
return 0 | |
} | |
let total = v; | |
const fn = (val) => { | |
if(val === undefined) { | |
return total | |
} | |
else { | |
total += val; | |
return fn | |
} | |
} | |
return fn | |
} | |
console.log(sum(2)(3)()) | |
console.log(sum(1)(2)()) | |
console.log(sum()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment