Skip to content

Instantly share code, notes, and snippets.

@richardcornish
Last active August 10, 2023 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardcornish/3b3b6cf1b7a597aaac20 to your computer and use it in GitHub Desktop.
Save richardcornish/3b3b6cf1b7a597aaac20 to your computer and use it in GitHub Desktop.
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