Created
December 19, 2016 23:48
-
-
Save sylvainpolletvillard/c754c6695cc84c38744dc10b6dfbb3e2 to your computer and use it in GitHub Desktop.
Hurray; Array subclass with hash destructuring for method callbacks, and a few helpers
This file contains 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
class Hurray extends Array { | |
forEach(callback){ | |
super.forEach.call(this, (...args) => callback(Hurray.iterator(...args))); | |
return this; // make forEach chainable | |
} | |
every(callback){ return super.every.call(this, (...args) => callback(Hurray.iterator(...args))) } | |
filter(callback){ return super.filter.call(this, (...args) => callback(Hurray.iterator(...args))) } | |
find(callback){ return super.find.call(this, (...args) => callback(Hurray.iterator(...args))) } | |
findIndex(callback){ return super.findIndex.call(this, (...args) => callback(Hurray.iterator(...args))) } | |
map(callback){ return super.map.call(this, (...args) => callback(Hurray.iterator(...args))) } | |
some(callback){ return super.some.call(this, (...args) => callback(Hurray.iterator(...args))) } | |
reduce(cb){ return super.reduce.call(this, (accu, ...args) => cb(Hurray.iterator(...args, accu))) } | |
reduceRight(cb){ return super.reduceRight.call(this, (accu, ...args) => cb(Hurray.iterator(...args, accu))) } | |
} | |
Hurray.from = array => new Hurray(...Array.from(array)); | |
Hurray.iterator = function(item, index, array, accumulator){ | |
const isFirst = index === 0, | |
isLast = index + 1 === array.length, | |
isOdd = index % 2 === 1, | |
isEven = index % 2 === 0; | |
return { // pass arguments as hash | |
item, index, isFirst, isLast, isOdd, isEven, array, accumulator | |
}; | |
}; | |
// ======= EXAMPLE USAGE ========= | |
const dalton = Hurray.from(["joe","william","jack","averell"]); | |
dalton.forEach(function({ item, index, isFirst, isLast, isOdd, isEven, array }){ | |
console.log({ item, index, isFirst, isLast, isOdd, isEven, array}) | |
}); | |
dalton.filter(({ isOdd }) => isOdd); | |
dalton.filter(({ isFirst, isLast }) => isFirst || isLast); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment