Skip to content
This repository has been archived by the owner on Feb 20, 2019. It is now read-only.

Commit

Permalink
feat(makeObjectIterable): Add makeObjectIterable function (#182)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ravi Soni authored and Kent C. Dodds committed Jul 11, 2018
1 parent 02fedc8 commit 695b8b9
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import isLeapYear from './leap-year'
import removeElementFromArray from './removeElementFromArray'
import generatePassword from './generate-password'
import tail from './tail'
import makeObjectIterable from './makeObjectIterable'

export {
reverseArrayInPlace,
Expand Down Expand Up @@ -132,4 +133,5 @@ export {
removeElementFromArray,
generatePassword,
tail,
makeObjectIterable,
}
32 changes: 32 additions & 0 deletions src/makeObjectIterable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export default makeObjectIterable

/**
* Original Source: https://stackoverflow.com/questions/48132121/how-to-make-iterable-object-in-javascript
*
* Makes a regular object iterable so that it can be used in constructs such
* as a for-of loop.
*
* @param {Object} obj - object on which iteration is desired
* @returns {Object} - returns the same object
*/
function makeObjectIterable(obj) {
Object.defineProperty(obj, Symbol.iterator, {
writable: false,
enumerable: false,
configurable: true,
value: function iteratorCreator() {
let idx = 0
const ks = Object.keys(obj)
return {
next: function nextElement() {
return {
value: obj[ks[idx++]],
done: idx > ks.length,
}
},
}
},
})

return obj
}
14 changes: 14 additions & 0 deletions test/makeObjectIterable.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import test from 'ava'
import {makeObjectIterable} from '../src'

test('check if the iterator returns correct values ', t => {
const myObj = {a: 1, b: 2, c: 'XKCD'}
const out = makeObjectIterable(myObj)
const a = []
const b = []
Object.keys(myObj).map(item => a.push(myObj[item]))
for (const v of out) {
b.push(v)
}
t.deepEqual(a, b)
})

0 comments on commit 695b8b9

Please sign in to comment.