Skip to content

Instantly share code, notes, and snippets.

@panuhorsmalahti
Created May 20, 2015 17:48
Show Gist options
  • Save panuhorsmalahti/c47ae6094876522cbf87 to your computer and use it in GitHub Desktop.
Save panuhorsmalahti/c47ae6094876522cbf87 to your computer and use it in GitHub Desktop.
Simple way to combine multiple elements in an array.
Array.prototype.squeeze = function (n, fn) {
const from = Object(this).slice();
const to = [];
while (n > 0 && from.length)
to.push(fn.apply(undefined, from.splice(0, n)));
return to;
}
// Convert [1, 2, 3, 4] to [1 + 2, 3 + 4]
var test = [1, 2, 3, 4];
console.log(JSON.stringify(test.squeeze(2, (a, b) => a + b)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment