Skip to content

Instantly share code, notes, and snippets.

@andrit
Last active August 11, 2018 19:48
Show Gist options
  • Save andrit/e318e655d82e5cd521a993700d7d73c2 to your computer and use it in GitHub Desktop.
Save andrit/e318e655d82e5cd521a993700d7d73c2 to your computer and use it in GitHub Desktop.
define a custom default @@iterator for an object and access with ES6 for...of
var myObj = {
  a:2,
  b:3
}

Object.defineProperty( myObj, Symbol.iterator, {
  enumerable: false,
  writable: false,
  configurable: true,
  value: function() {
    var o = this;
    var idx = 0;
    var ks = Object.keys( 0 );
    return {
      next: function() {
        return {
          value: o[ks[idx++]],
          done: (idx > ks.length)
        };
      }
    };
  }
} );

//iterate 'myObj' maually
var it = myObj[Symbol.iterator]();
it.next(); //{ value: 2, done: false }
it.next(); //{ value: 3, done: false }
it.next(); //{ value: undefined, done: true }

// iterate 'myObj with 'for...of'
for(var v of myObj) {
  console.log(v);
}
//2
//3
var Foo = {
	*[Symbol.iterator]() {
		for(let[idx, val] of this.nums.entries()) {
        yield label =>
          `${label}: ${val}
          (${idx+1} / ${this.nums.length})`;
    }
},
  bar([x =1, y = 2, ...nums] = []) {
  this.nums = [x,y,...nums];
  }
};

Foo.bar([10, 20, 30, 40, 50]);

for (let f of Foo) {
console.log( f("Foo") );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment