Skip to content

Instantly share code, notes, and snippets.

@donabrams
Created May 7, 2021 08:55
Show Gist options
  • Save donabrams/f61d6fcf63fff7d9db4ae56508aedb9c to your computer and use it in GitHub Desktop.
Save donabrams/f61d6fcf63fff7d9db4ae56508aedb9c to your computer and use it in GitHub Desktop.
addKata
var addTwo = add(2);
addTwo; // 2
addTwo + 5; // 7
addTwo(3); // 5
addTwo(3)(5); // 10
var add = function(inc = 0, value = 0) {
var f = function(n) {
// In the case of no arguments there are two possibilities:
// 1. return this so that the object is returned (chaining is enabled ie this works: add(2)()()(3)(4))
// 2. return a number so that the return type is a number (return type consistency ie this returns a number: add(2)() )
//
// I chose option 1 here
return arguments.length === 0 ? this : add(0, n + value + inc);
}
f.valueOf = function() { return Number.prototype.valueOf.apply(value + inc, arguments); }
f.toString = function() { return Number.prototype.toString.apply(value + inc, arguments); }
f.prototype = Number;
return f;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment