Search code examples
javascriptiteratorprototypegeneratorfor-of-loop

For-of Loop Default Iterator Function


Consider this simple generator function defined on Object.prototype:

Object.prototype.defineProperty(Object.prototype, 'pairs', {
    enumerable: false,
    * value( ) {
        for (const key in this)
            yield [ key, this[key] ];
} });

Of course, it could be used like this:

const object = { goats_teleported: 42 };

for (const [ key, value ] of object.pairs());

But I wonder if there any way to assign pairs function to object prototype, so it will be automaticly fired in for-of loop without explicit call; just like this:

for (const [ key, value ] of object);

Any ideas?


Solution

  • Put the generator on Object.prototype[Symbol.iterator]:

    Object.prototype[Symbol.iterator] = function* pairs() {
      for (const key in this) yield [ key, this[key] ];
    };
    const object = { goats_teleported: 42, foo: 'fooval' };
    
    for (const [ k, v ] of object) {
      console.log(k, v);
    }