Skip to content

Instantly share code, notes, and snippets.

@richardcornish

richardcornish/Adder adder

Last active Aug 29, 2015
Embed
What would you like to do?
Uses variable-length arguments and closures to create an adding adding function
// H5BP Front-end Developer Interview Questions
// https://github.com/h5bp/Front-end-Developer-Interview-Questions#jscode
// Usage:
// 1 = add(1)();
// 3 = add(1, 2)();
// 6 = add(1, 2)(3);
// 10 = add(1, 2)(3, 4);
// 0 = add()();
var add = function () {
var first = 0;
for (var i = 0; i < arguments.length; i++) {
first += arguments[i];
}
return function () {
var second = 0;
for (var i = 0; i < arguments.length; i++) {
second += arguments[i];
}
return first + second;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment