Skip to content

Instantly share code, notes, and snippets.

@ryansukale
Last active May 29, 2016 22:58
Show Gist options
  • Save ryansukale/c655a6462d9d8876ab3e to your computer and use it in GitHub Desktop.
Save ryansukale/c655a6462d9d8876ab3e to your computer and use it in GitHub Desktop.
Custom iterables in es6
var example = {one : 'something', two: 'somethingElse'};
var test = {}
test[example.one]: true;
test[example.two]: function () { console.log('so verbose');}
console.log(test.something); // true
test.somethingElse(); // Prints 'so verbose'
var example = {one : 'something', two: 'somethingElse'};
var test = {
[example.one]: true,
[example.two]: function () { console.log('omg!');},
};
console.log(test.something); // Prints true
test.somethingElse(); // Prints omg!
var countdown = {max: 3, ....};
for (let i of countdown) { // This is what we want to achieve
console.log(i);
}
// We expect the above code to print 3, 2, 1, 0
function countdownIterator(max) {
// This function returns an object that implements the next() function
// The next function is expected to return data in a specific format
// as you can see below
return {
next() { // This function is automatically invoked by for-of loops
if (max > -1) {
return {value: max--}; // As long as you have a value
} else {
return {done: true}; // When you are out of values
}
}
};
}
var countdown = {
max: 3,
[Symbol.iterator]() { // This key is the magic glue
// We invoke the function to get an object with the next() function and return it
return countdownIterator(this.max);
}
};
for (let i of countdown) {
console.log(i);
}
var countdown = {
max: 3,
[Symbol.iterator]() {
// Its ok to return 'this' because it implements the next function.
return this;
},
next() {
if (this._max === undefined) {
this._max = this.max;
}
if (this._max > -1) {
return {value: this._max--}; // As long as you have a value
} else {
return {done: true}; // When you are out of values
}
}
};
for (let i of countdown) {
console.log(i);
break;
}
// Prints 3
for (let i of countdown) {
console.log(i);
break;
}
var countdown = {
....
....
return() {
this._max = undefined;
return {done: true};
}
}
for (let i of countdown) {
console.log(i);
break;
}
// Prints 3
for (let i of countdown) {
console.log(i);
break;
}
// Prints 3 because the countdown was reset!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment