Created
May 7, 2021 08:55
-
-
Save donabrams/f61d6fcf63fff7d9db4ae56508aedb9c to your computer and use it in GitHub Desktop.
addKata
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
var addTwo = add(2); | |
addTwo; // 2 | |
addTwo + 5; // 7 | |
addTwo(3); // 5 | |
addTwo(3)(5); // 10 |
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
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