Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C6 · Μάθημα 5
ΕργασίαDefine function* naturals() (infinite 1,2,3,...) and function* take(iter, n) that yields first n items. Log [...take(naturals(), 5)].join(','). Then count squares with function* squares() that yields n*n for each natural, log [...take(squares(), 4)].join(',').

Lazy infinite sequences

175 XP10 min
Θεωρία

Generators don't have to end

A generator only computes the next value when you ask. An infinite while (true) loop with yield is perfectly fine — the runtime never gets stuck because each yield pauses execution.

function* naturals() {
  let n = 1;
  while (true) yield n++;
}

You can NOT for-of an infinite generator without a break. You CAN take a finite prefix:

function* take(iter, n) {
  let i = 0;
  for (const x of iter) {
    if (i++ >= n) return;
    yield x;
  }
}

console.log([...take(naturals(), 5)]); // [1, 2, 3, 4, 5]

Why lazy matters

  • Memory — you never materialize the whole sequence.
  • Composition — take(filter(map(naturals(), x => x*x), x => x > 50), 3) walks naturals exactly until 3 results are found, no more.
  • This is how reactive frontend frameworks model streams of events under the hood.

The pattern in production

Pagination, event streams, message queues, anything-with-backpressure. Lesson C6-08 shows the async version that powers paginated APIs.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.