Last active
August 29, 2015 14:20
-
-
Save kjlape/fb51ad7e08c470d80a27 to your computer and use it in GitHub Desktop.
Variadic js...
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
| Function.prototype.variadic = function () { | |
| var self = this | |
| return function () { | |
| return self.apply(self, | |
| self.length == 1 ? | |
| [arguments] : | |
| Array.prototype.reduce.call(arguments, function (a,x,i) { | |
| return (i + 1 < self.length ? | |
| a[i] = x : | |
| (rest = a[self.length -1], | |
| typeof rest !== 'undefined' && rest != null) ? | |
| rest.push(x) : | |
| a[self.length -1] = [x]), a | |
| }, [])) | |
| } | |
| } | |
| Function.prototype.spread = function (a) { | |
| return this.apply(null, a) | |
| } | |
| var snoop = function (args) { | |
| console.log.apply(console, args) | |
| return args[0] | |
| }.variadic() | |
| var car = function (car, cdr) { return car }.variadic() | |
| var cdr = function (car, cdr) { return cdr }.variadic() | |
| var sum = function (car, cdr) { return cdr ? car + sum.spread(cdr) : car }.variadic() | |
| snoop( | |
| car(1,2,3,4,5), | |
| cdr(1,2,3,4,5), | |
| sum(1,2,3,4,5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment