Set Key In A Javascript Generator Function
Solution 1:
If you want to yield both the key and the value, you'd need to yield an array with two items, e.g.
yield [key, this[key]];
then the .value
on the object would be a key/value pair.
Also note that this behavior is similar to what you get from Object.entries(james)
which is a new function added in ES2017, except that it returns an Array
.
If explicitly want
.next()
to return an object with both key
, value
and done
, then the answer is you can't do that with a generator. That's not the API that generators provide, and it's not the iterator protocol defined in ES6, so you shouldn't be using an iterator to try to do this.
You could certainly do
james.makeCustomThing = function(){
const pairs = [];
for (const key inthis) pairs.push([key, this[key]]);
return {
next(){
if (pairs.length === 0) return {done: true};
let [key, value} = pairs.shift();
return {key, value, done: false};
},
};
};
but then it's not an iterator anymore, it's just a custom thing you've defined yourself.
Solution 2:
You can't do it. The interface for iterators in ES6 is unchangeable:
interface IteratorResult {
done: boolean;
value: any;
}
interface Iterator {
next(): IteratorResult;
}
interface Iterable {
[Symbol.iterator](): Iterator
}
And generators work only with it. Whatever you yield it's going to be in value
.
Solution 3:
I modified @jack.the.ripper code to make use of Object.keys and next with arrow function, so we can make use of this.
const james = {
name: 'James',
height: `5'10"`,
weight: 185
};
james[Symbol.iterator] = function (){
const keys = Object.keys(this)
return {
next: () => {
let key = keys.shift();
return {value: this[key], key, done:keys.length===0};
}
}
}
let iterator = james[Symbol.iterator]();
console.log(iterator.next().value); // 'James'console.log(iterator.next().value); // `5'10`console.log(iterator.next().value); // 185
Post a Comment for "Set Key In A Javascript Generator Function"