Sobes.tech
Middle

Kuidas töötavad JavaScriptis generaatorid võrreldes tavaliste funktsioonidega?

sobes.tech AI

Vastus AI-lt

Generators in JavaScript are functions that can pause their execution and return intermediate values using the yield keyword. Unlike regular functions, which execute fully and return a single value, generators allow creating iterators with lazy generation of values.

Example of a generator:

function* countUpTo(max) {
  let count = 1;
  while (count <= max) {
    yield count; // pauses execution and returns the value
    count++;
  }
}

const counter = countUpTo(3);
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3
console.log(counter.next().done);  // true

Therefore, generators are useful for working with sequences of data that do not need to be computed immediately in their entirety.