xxxxxxxxxx
const iterableXx = {
[Symbol.iterator]: function* () {
yield 1;
yield 2;
}
};
console.log([iterableX]); // [1, 2]
xxxxxxxxxx
function* idMaker() {
var index = 0;
while (true)
yield index++;
}
var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
// ...
xxxxxxxxxx
function* expandSpan(xStart, xLen, yStart, yLen) {
const xEnd = xStart + xLen;
const yEnd = yStart + yLen;
for (let x = xStart; x < xEnd; ++x) {
for (let y = yStart; y < yEnd; ++y) {
yield {x, y};
}
}
}
//this is code from my mario game I dont think this code is functional
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* generateRange(end, start = 0, step = 1) {
let x = start - step;
while(x < end - step) yield x += step;
}
const gen5 = generateRange(5);
let x = gen5.next();
while (!x.done) {
console.log(x.value);
x = gen5.next();
} // Logs: 0, 1, 2, 3, 4
xxxxxxxxxx
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
console.log(gen.next().value); // Output: 1
console.log(gen.next().value); // Output: 2
console.log(gen.next().value); // Output: 3
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
// define a generator function
function* generator_function() {
..
}
// creating a generator
const generator_obj = generator_function();
xxxxxxxxxx
function* generateSequence() {
yield 1; // Pause and return 1
yield 2; // Pause and return 2
yield 3; // Pause and return 3
}
// Create an instance of the generator function
const generator = generateSequence();
// Calling `next()` on the generator will resume the function and return the next value
console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3