xxxxxxxxxx
//- With a generator function, values are not evaluated
//until they are needed.
//- Therefore a generator allows us to define a potentially
//infinite data structure.
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator(); // "Generator { }"
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
xxxxxxxxxx
function* g(){ //or function *g(){}
console.log("First");
yield 1;
console.log("second");
yield 2;
console.log("third");
}
let generator=g();
generator.next();
generator.next();
xxxxxxxxxx
function* myGenerator(start = 0, stop = 100, step = 5) {
for (let i = start; i <= stop; i += step) {
yield i;
}
}
for (let v of myGenerator()) {
console.log(v);
}
xxxxxxxxxx
// generator function in javascript
// The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
function* generator(i) {
yield i;
yield i + 10;
}
const gen = generator(10);
console.log(gen.next().value);
// expected output: 10
console.log(gen.next().value);
// expected output: 20
console.log(gen.next().value);
// expected output: undefined
xxxxxxxxxx
function* generateCharacters(word) {
for (const char of word) {
yield char;
}
}
// Example usage:
const inputWord = "JavaScript";
const charGenerator = generateCharacters(inputWord);
console.log(charGenerator.next());
console.log(charGenerator.next());
console.log(charGenerator.next());
console.log(charGenerator.next());
console.log(charGenerator.next());
xxxxxxxxxx
function* makeRangeIterator(start = 0, end = 100, step = 1) {
let iterationCount = 0;
for (let i = start; i < end; i += step) {
iterationCount++;
yield i;
}
return iterationCount;
}
xxxxxxxxxx
// define a generator function
function* generator_function() {
..
}
// creating a generator
const generator_obj = generator_function();
generators javascript
xxxxxxxxxx
function* g(){ //or function *g(){}
console.log("First");
yield 1;
console.log("second");
yield 2;
console.log("third");
}
let generator=g();
generator.next(); // Output First
generator.next(); // Output second
Generators compute their yield ed values on demand, which allows them to efficiently represent sequences that are expensive to compute