Skip to content

Instantly share code, notes, and snippets.

@eligrey
Last active August 8, 2022 05:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eligrey/105c0622e1c224f30029a30a05fa6a7a to your computer and use it in GitHub Desktop.
Save eligrey/105c0622e1c224f30029a30a05fa6a7a to your computer and use it in GitHub Desktop.
spreadify: add a universal iterator to any array-like object
/** Alternative spreadify implementation with `...spreadify.once` */
const spreadify = {
/** Always spread */
*[Symbol.iterator](): any {
delete this[Symbol.iterator];
yield* this.once[Symbol.iterator].call(this);
this[Symbol.iterator] = this.once[Symbol.iterator];
},
once: {
/** Spread once */
*[Symbol.iterator](): any {
delete this[Symbol.iterator];
// eslint-disable-next-line no-restricted-syntax
for (const item of Array.from(this)) {
yield item;
}
},
},
};
export default spreadify;
/**
* spreadify: add a universal iterator to any array-like object.
*
* @example
* const list = [...{...nonIterableArrayLike, ...spreadify}];
* for (const item of list) {
* item.doStuff();
* }
*/
const spreadify = {
/** General array-like iterator */
*[Symbol.iterator](): any {
const iterator = this[Symbol.iterator];
delete this[Symbol.iterator];
// eslint-disable-next-line no-restricted-syntax
for (const item of Array.from(this)) {
yield item;
}
this[Symbol.iterator] = iterator;
},
};
export default spreadify;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment