Created
October 7, 2017 17:28
-
-
Save johirbuet/a79a4eb5b5265874b75787eb8cd49298 to your computer and use it in GitHub Desktop.
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
/* | |
* Programming Quiz: Make An Iterable Object | |
* | |
* Turn the `james` object into an iterable object. | |
* | |
* Each call to iterator.next should log out an object with the following info: | |
* - key: the key from the `james` object | |
* - value: the value of the key from the `james` object | |
* - done: true or false if there are more keys/values | |
* | |
* For clarification, look at the example console.logs at the bottom of the code. | |
* | |
* Hints: | |
* - Use `Object.keys()` to store the object's properties in an array. | |
* - Each call to `iterator.next()` should use this array to know which property to return. | |
* - You can access the original object using `this`. | |
* - To access the values of the original object, use `this` and the key from the `Object.keys()` array. | |
*/ | |
const james = { | |
name: 'James', | |
height: `5'10"`, | |
weight: 185, | |
[Symbol.iterator]: function () { | |
let keys = Object.keys(this); | |
let values = Object.keys(this).map((k) => this[k]); | |
let index = 0; | |
return { | |
next: function () { | |
return { | |
value: values[index], | |
key: keys[index], | |
done: index++ >= keys.length - 1 | |
}; | |
} | |
} | |
} | |
}; | |
let iterator = james[Symbol.iterator](); | |
console.log(iterator.next().value); // 'James' | |
console.log(iterator.next().value); // `5'10` | |
console.log(iterator.next().value); // 18 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment