Skip to content

Instantly share code, notes, and snippets.

@jesusgoku
Created August 12, 2019 16:13
Show Gist options
  • Save jesusgoku/8861e768f718abfd0876c845c662c18f to your computer and use it in GitHub Desktop.
Save jesusgoku/8861e768f718abfd0876c845c662c18f to your computer and use it in GitHub Desktop.
Implement Symbol.Iterator for objects
/**
* Apply to Symbol.iterator on object to enable iteration
*
* @param field values, keys, entries
*
* @return {Function}
*/
function ObjectIteraror(field) {
if (!['keys', 'values', 'entries'].includes(field)) {
throw new Error('Incorrect field value, available values: keys, values, entries');
}
return function() {
return {
_entries: Object[field](this),
_currentIndex: 0,
next() {
const value = this._entries[this._currentIndex];
const done = this._currentIndex === this._entries.length;
this._currentIndex += 1;
return { value, done };
},
};
}
}
const ObjectIteratorValues = ObjectIteraror('values');
const ObjectIteratorKeys = ObjectIteraror('keys');
const ObjectIteratorEntries = ObjectIteraror('entries');
export {
ObjectIteraror,
ObjectIteratorKeys,
ObjectIteratorValues,
ObjectIteratorEntries,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment