This repository has been archived by the owner on Feb 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 603
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(makeObjectIterable): Add makeObjectIterable function (#182)
- Loading branch information
Ravi Soni
authored and
Kent C. Dodds
committed
Jul 11, 2018
1 parent
02fedc8
commit 695b8b9
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
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 | ||
} |
This file contains 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
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) | ||
}) |