Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Created December 19, 2016 23:48
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 sylvainpolletvillard/c754c6695cc84c38744dc10b6dfbb3e2 to your computer and use it in GitHub Desktop.
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
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