Created
June 24, 2013 05:03
-
-
Save cjavdev/5847834 to your computer and use it in GitHub Desktop.
I've been working on the curriedSum exercise from intro-js/arguments.md. I've got the following recursive solution working, but not sure how the iterative version is supposed to work.
This file contains 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 currySumRecursive(n, sum) { | |
//sum will not be passed in on the first call | |
// so we set it to 0. | |
if(sum === undefined) { | |
sum = 0; | |
} | |
//if this is the last recursive call | |
// return a simple function that returns | |
// the sum | |
if(n===1) { | |
return function(x) { | |
return sum + x; | |
} | |
} | |
//otherwise recursively call currySumRecursive | |
// passing the sum along until there are | |
// n curried (correct usage of term curried?) functions. | |
else { | |
return function(x) { | |
return currySumRecursive(n-1, x + sum); | |
} | |
} | |
} | |
var sumRecursive = currySumRecursive(1); | |
console.log("calling recursive sum (3): " + sumRecursive(3)); | |
var sumRecursive2 = currySumRecursive(3); | |
console.log("calling recursive sum (1)(2)(3): " + sumRecursive2(1)(2)(3)); | |
function currySumIterative(n) { | |
var s = function(nums) { | |
var sum = 0; | |
nums.forEach(function(num) { | |
sum += num; | |
}); | |
return sum; | |
} | |
var args = undefined; | |
var doll = function(x) { | |
if(args === undefined) { | |
args = [].slice.call(arguments, 0); | |
} | |
//eventually we will get a function | |
// that looks like sum(1,2,3,4) | |
// if n was 4. then we would like to sum | |
// the arguments | |
if(args.length === n) { | |
return s.call(null, args); | |
} else { | |
//not sure what should go here | |
// ideally we want to return fn { return fn {return fn}} | |
// until we get args.len = n | |
return function(y) { | |
args.push(y); | |
//?? | |
return doll(args); | |
} | |
} | |
} | |
return doll; | |
} | |
var sumIterative = currySumIterative(1); | |
console.log("calling iterative sum (2): " + sumIterative(2)); | |
var sumIterative2 = currySumIterative(3); | |
console.log("calling iterative sum (1)(2)(3): " + sumIterative(1)(2)(3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment