Skip to content

Instantly share code, notes, and snippets.

@alexspark
Created December 15, 2017 05:00
Show Gist options
  • Save alexspark/0f38d0d156ebb02571b22f2a5c4e22ca to your computer and use it in GitHub Desktop.
Save alexspark/0f38d0d156ebb02571b22f2a5c4e22ca to your computer and use it in GitHub Desktop.
LearnES6part2 created by alexspark - https://repl.it/@alexspark/LearnES6part2
// iterators
const fib = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[ pre, cur ] = [cur, pre + cur];
return {
done: false, value: cur
};
}
};
}
};
for (let n of fib) {
if (n > 100) { break; }
console.log(n);
}
// generators
const fibb = {
*[Symbol.iterator]() {
let pre = 0, cur = 1;
for (;;) {
[ pre, cur ] = [ cur, pre + cur];
yield cur
}
}
}
for (let n of fibb) {
if (n > 100) { break; }
console.log(n);
}
// function generator
const steps = function*(start, end) {
while (start <= end) {
yield start
start += 1;
}
};
for (let n of steps(1, 25)) {
console.log(n);
}
// generator matching
let numbers = [ ...steps(100, 110)];
let [n1, n2, n3, ...rest] = steps(200, 210);
console.log(...numbers);
console.log(n1, n2, n3, ...rest);
// generator methods
class Cat {
constructor(name, owner) {
this._name = name;
this._owner = owner;
this._meowCount = 0;
}
set name(n) { this._name = n; }
get name() { return this._name; }
* meow() {
for(;;) {
this._meowCount += 1;
console.log(`MEOW! (${this._meowCount})`)
yield this._meowCount;
}
}
}
const b = new Cat('bella', 'alex')
for (m of b.meow()) {
if(m > 10) { break; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment