Tags

Generators

Generators

0 lessons
3 code snippets
2 question banks
1 community item

generators

Code Snippets

3 snippets
Code Snippet

Generate a Numeric Range

JavaScript still has no built-in `range()` like Python, so every codebase eventually grows its own. This snippet shows the canonical `Array.from` trick for `[0, n)`, a `start, end, step` variant that handles negative steps, and a lazy generator for huge ranges where allocating the full array is wasteful. Use it for pagination, retries, table rows, and any test fixture that needs N of something.

JavaScript
arrays
utility
generators
code-template

1.1k

14

Easy
Code Snippet

Fibonacci: Iterative, Recursive, Memoized, Generator

Fibonacci is the canonical exercise for comparing iteration, recursion, memoization, and lazy evaluation. The iterative for-loop is the production answer, naive recursion is the cautionary tale (exponential cost), memoization fixes the recursion to linear time, and a generator yields an infinite stream you can `take(n)` from. Above index 78, switch to BigInt to avoid floating-point precision loss.

JavaScript
fibonacci
recursion
memoization
generators

808

14

Medium
Code Snippet
Premium

Generators as State Machines

Generators turn an explicit `switch (state)` block into a function whose own pause points encode the state. This snippet shows three flavors: a finite-state machine driven by `next(event)` for transitions, a step-by-step async sequencer that pauses between phases, and a richer machine with entry/exit side effects plus an unexpected-event handler. Reach for this when your control flow has a small, explicit set of states and you want the language to enforce them for you.

JavaScript
generators
state-machine
control-flow

1k

26

Hard

Question Banks

2 items
Question Bank
Premium

JavaScript Class, Generator, and Strict-Mode Traces

Four advanced traces covering generator iterator state, the `_id` private-by-convention pattern, strict mode + `Object.defineProperty` enumerability, and try/catch + `var` scope leaks.

JavaScript
quiz
generators
classes
js-strict-mode

894

9

Hard
Question Bank
Premium

Generators and Iterators Quiz

Practice the iterator protocol from both sides: write an infinite Fibonacci generator, an async iterable, a `[Symbol.iterator]` implementation, and a `for...of` consumer.

JavaScript
quiz
generators
iterators
js-language

244

3

Hard