Last active
February 15, 2021 10:06
-
-
Save jmporchet/c9e1f6d1d037ece5cab04c68eee0db5f to your computer and use it in GitHub Desktop.
Object iterator property
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 obj = { | |
sub: { | |
array: [] | |
}, | |
[Symbol.iterator]() { | |
let index = 0; | |
return { | |
next: () => { | |
// you could insert custom logic here, like stepping 3 by 3, filtering, etc. | |
if ( index >= this.sub.array.length ) return { done: true } | |
// use index value then increment it | |
return { value: this.sub.array[index++], done: false } | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a nifty trick I was asked about in an interview.
I didn't know about it and failed the interview, but at least I learned something :-)
It's especially useful when you can't or don't want to modify a big data source and are mainly interested in one part of it.
You can then use it with the spread operator, or with a for...of loop to get the
next()
value out of it