Created
August 29, 2017 22:39
-
-
Save karanlyons/26ec6657a2134b91f5ab55a435811d89 to your computer and use it in GitHub Desktop.
splatify.js: Add some venom to your coffee
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 splatify(func) { | |
args_string = func.toString().split('(')[1].split(')')[0].split(',').map(function(s) { return s.trim(); }); | |
if (args_string.length && args_string[args_string.length - 1] === 'splat_args') { | |
pivot = args_string.length - 1; | |
return function () { | |
if (arguments.length > pivot + 1) { | |
args = Array.prototype.slice.call(arguments, 0, pivot); | |
args.push(Array.prototype.slice.call(arguments, pivot)); | |
return func.apply(this, args); | |
} else { | |
args = Array.prototype.slice.call(arguments); | |
for (i=args.length; i < pivot; i++) { args.push(undefined); } | |
args.push([]); | |
return func.apply(this, args); | |
} | |
} | |
} else { | |
return func; | |
} | |
} |
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
// The usage is "DO NOT" | |
t = splatify(function t(foo, bar, splat_args) { | |
console.log("foo=" + foo + ", bar=" + bar + ", splat_args=[" + splat_args.toString() + "]"); | |
}); | |
t(1) // foo=1, bar=undefined, splat_args=[] | |
t(1, 2) // foo=1, bar=2, splat_args=[] | |
t(1, 2, 3) // foo=1, bar=2, splat_args=[3] | |
t(1, 2, 3, 4) // foo=1, bar=2, splat_args=[3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because, as per usual, IE lets us down.