Skip to content

Instantly share code, notes, and snippets.

@cameronhunter
Created July 23, 2015 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronhunter/7358a5bc6889cd0ad60c to your computer and use it in GitHub Desktop.
Save cameronhunter/7358a5bc6889cd0ad60c to your computer and use it in GitHub Desktop.
Array#bucket for JavaScript in ES6
Array.prototype.bucket = function(fn) {
const results = [...Array(fn.length)].map(() => []);
const buckets = results.map(bucket => bucket.push.bind(bucket));
const noop = () => {};
this.forEach(item => (fn.apply(item, buckets) || noop)(item));
return results;
};
const [even, odd] = [1,2,3,4,5,6].bucket(function(even, odd) { return this % 2 == 0 ? even : odd; });
const [fizz, buzz, fizzbuzz] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].bucket(function(fizz, buzz, fizzbuzz) {
const [isFizz, isBuzz] = [this % 3 == 0, this % 5 == 0];
if (isFizz && isBuzz) return fizzbuzz
if (isFizz) return fizz;
if (isBuzz) return buzz;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment