Skip to content

Instantly share code, notes, and snippets.

View vldvel's full-sized avatar

Vlad vldvel

  • Amsterdam
View GitHub Profile
class MyClass {
*generator() {}
* generator() {}
}
const obj = {
*generator() {}
* generator() {}
}
function withReturn(a) {
let b = 5;
return a + b;
b = 6; // we will never re-assign b
return a * b; // and will never return new value
}
withReturn(6); // 11
withReturn(6); // 11
function * withYield(a) {
let b = 5;
yield a + b;
b = 6; // it will be re-assigned after first execution
yield a * b;
}
const calcSix = withYield(6);
calcSix.next().value; // 11
function * generator() {
yield 5;
}
const gen = generator();
gen.next(); // {value: 5, done: false}
gen.next(); // {value: undefined, done: true}
gen.next(); // {value: undefined, done: true} - all other calls will produce the same result
function * generator(arg = 'Nothing') {
yield arg;
}
const gen0 = generator(); // OK
const gen1 = generator('Hello'); // OK
const gen2 = new generator(); // Not OK
generator().next(); // It will work, but every time from the beginning
function * generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
gen.next(); // {value: 1, done: false}
gen.next(); // {value: 2, done: false}
function * generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
gen.return(); // {value: undefined, done: true}
gen.return('Heeyyaa'); // {value: "Heeyyaa", done: true}
function * generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
gen.throw('Something bad'); // Error Uncaught Something bad
gen.next(); // {value: undefined, done: true}
const strings = document.querySelectorAll('.string');
const btn = document.querySelector('#btn');
const className = 'darker';
function * addClassToEach(elements, className) {
for (const el of Array.from(elements))
yield el.classList.add(className);
}
const addClassToStrings = addClassToEach(strings, className);
function * anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
function * generator(i) {
yield* anotherGenerator(i);
}