Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
splatify.js: Add some venom to your coffee
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;
}
}
// 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]
@karanlyons

This comment has been minimized.

Copy link
Owner Author

commented Aug 29, 2017

Because, as per usual, IE lets us down.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.