Skip to content

Instantly share code, notes, and snippets.

@jmporchet
Last active February 15, 2021 10:06
Show Gist options
  • Save jmporchet/c9e1f6d1d037ece5cab04c68eee0db5f to your computer and use it in GitHub Desktop.
Save jmporchet/c9e1f6d1d037ece5cab04c68eee0db5f to your computer and use it in GitHub Desktop.
Object iterator property
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 }
}
}
}
}
@jmporchet
Copy link
Author

jmporchet commented Feb 11, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment