Last active
September 13, 2019 08:50
-
-
Save krishna2nd/97d09b7585697dc9ab912a6c3ab8c6e6 to your computer and use it in GitHub Desktop.
Curry function to find sum of integers with different parameter usage
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() { | |
let args = [...arguments]; | |
if (args.length > 2) { | |
let sumValue = 0; | |
args.forEach(arg => { | |
sumValue += arg; | |
}); | |
return sumValue; | |
} | |
if (args.length === 2) { | |
return function() { | |
return sum.apply(this, [...args, ...arguments]); | |
}; | |
} | |
function single() { | |
if (arguments.length === 0) { | |
return sum.apply(this, args); | |
} | |
args = [...args, ...arguments]; | |
return single; | |
}; | |
return single; | |
} | |
console.log(sum(2, 3, 4)); | |
console.log(sum(2, 3)(4)); | |
console.log(sum(2, 3, 4, 0, 1)); | |
console.log(sum(2)(3)(4)()); | |
console.log(sum(2)(3)(4)(0)(1)()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment