Skip to content

Commit f9046d4

Browse files
committed
Infinite Fibonacci sequence using generators
1 parent 3743a06 commit f9046d4

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

‎3-generators.js

+29-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@
1111
/**
1212
* What are generators?
1313
* Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
14+
*
15+
* In computer science, a generator is a special routine that can be used to control the iteration behaviour of a loop. In fact, all generators are iterators.
16+
* A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values.
17+
* However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time,
18+
* which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.
19+
*
1420
*/
1521

1622
// Two things distinguish genFunc from a normal function declaration:
@@ -345,4 +351,26 @@ genObj1.throw(new Error('Problem!'));
345351
function* genFunc() {
346352
}
347353
genFunc().throw(new Error('Problem!'));
348-
// Error: Problem!
354+
// Error: Problem!
355+
356+
357+
/**
358+
* Extras:
359+
* Infinite Fibonacci sequence using generators
360+
*/
361+
362+
function* fibonacci() {
363+
let [prev, curr] = [0, 1];
364+
while (true) {
365+
yield curr;
366+
[prev, curr] = [curr, prev + curr];
367+
}
368+
}
369+
370+
var gen = fibonacci();
371+
console.log(gen.next().value); // 1
372+
console.log(gen.next().value); // 1
373+
console.log(gen.next().value); // 2
374+
console.log(gen.next().value); // 3
375+
console.log(gen.next().value); // 5
376+
console.log(gen.next().value); // 8

0 commit comments

Comments
 (0)