Skip to content

Instantly share code, notes, and snippets.

@koozdra
Last active November 11, 2017 16:25
Show Gist options
  • Save koozdra/3fccfc0907ab0eb78c96 to your computer and use it in GitHub Desktop.
Save koozdra/3fccfc0907ab0eb78c96 to your computer and use it in GitHub Desktop.
Javascript Spreadable Functions
function spreadable(f) {
return function() {
return f.apply(null, _.flattenDeep(arguments))
};
}
var a = spreadable(function (a, b, c, d, e, f, g, h) {
return [a, b, c, d, e, f, g, h];
});
// regular
a(1, 2, 3, 4, 5, 6, 7, 8);
// [1, 2, 3, 4, 5, 6, 7, 8]
// handle empty arrays
a([1,2,3],[4], 5, [], [[], []]);
// [1, 2, 3, 4, 5, undefined, undefined, undefined]
// nested arrays
a([[1],[[2],[3]]], [4], 5, [[[[[6,7]]],8]]);
// [1, 2, 3, 4, 5, 6, 7, 8]
// more arguments than needed
a([[1],[[2],[3]]], [4], 5, [[[[[6,7]]]]],8,9);
// [1, 2, 3, 4, 5, 6, 7, 8]
// less arguments than needed (should fill the rest with undefineds)
a();
// [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
var drawPixel = spreadable(function(x,y,r,g,b,a,ctx){});
var pixel = [10,10];
var white = [255, 255, 255, 255];
drawPixel(pixel, white, ctx);
//Update from the future: spread operator
drawPixel(...pixel, ...white, ctx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment