Last active
August 8, 2022 05:41
-
-
Save eligrey/105c0622e1c224f30029a30a05fa6a7a to your computer and use it in GitHub Desktop.
spreadify: add a universal iterator to any array-like object
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
/** 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; |
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
/** | |
* 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