Created
July 23, 2015 01:53
-
-
Save cameronhunter/7358a5bc6889cd0ad60c to your computer and use it in GitHub Desktop.
Array#bucket for JavaScript in ES6
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
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; | |
}; |
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
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