Skip to content

loop

The loop() function creates a custom generator using a loop function. It lets you generate sequences of values lazily.

Interactive example

Syntax

typescript
function loop<
	GenericRawExitOutput extends any = undefined,
	GenericRawNextOutput extends any = undefined,
>(
	loop: (params: GeneratorLoopParams<GenericRawNextOutput>) =>
		| LoopOutputNextResult<GenericRawNextOutput>
		| LoopOutputNextResult<undefined>
		| LoopOutputExistResult<GenericRawExitOutput>
		| LoopOutputExistResult<undefined>
): Generator<
	Exclude<GenericRawExitOutput | GenericRawNextOutput, undefined>,
	unknown,
	unknown
>

Parameters

  • loop: Function called at each iteration that receives:
    • count: Index of the current iteration
    • previousOutput: Value returned by the previous iteration
    • next(value?): Continues the loop and emits a value
    • exit(value?): Ends the loop and emits an optional final value

Return value

A Generator that emits the values passed to next() and exit().

See also

  • asyncLoop - Asynchronous version of loop
  • execute - Consumes a generator
  • map - Transforms the elements of a generator

Sources

Released under the MIT license.