Created
August 12, 2019 16:13
-
-
Save jesusgoku/8861e768f718abfd0876c845c662c18f to your computer and use it in GitHub Desktop.
Implement Symbol.Iterator for objects
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
/** | |
* 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