Last active
July 7, 2016 15:27
-
-
Save nobitagit/02f754589732a7fd8c1253336f244f1b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Lessons learned implementing a simple adder. | |
| * Array functions do not have the arguments object | |
| **/ | |
| var add = function() { | |
| var args = Array.prototype.slice.call(arguments) | |
| return args.reduce((all, item) => { | |
| return all + item; | |
| }, 0); | |
| } | |
| add(1,2); // -> 3 | |
| var add2 = () => { | |
| var args = Array.prototype.slice.call(arguments) | |
| return args.reduce((all, item) => { | |
| return all + item; | |
| }, 0); | |
| } | |
| add2(1,2); // -> throws error as arguments is undefined | |
| // lazy eval of arguments | |
| var add = function(param1) { | |
| return function(param2) { | |
| return param1 + param2 | |
| } | |
| }; | |
| add(4)(2); // 6 | |
| var addTwo = add(2); | |
| addTwo(4); // 6 | |
| addTwo(6); // 8 | |
| // ES6 syntax one-liner | |
| var add = x => y => x + y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment