Represents a lazy-evaluated value that is computed only when needed. Lazy

Example: Usage of the Lazy

// Create a Lazy instance that represents the computation of doubling a number.
const lazyDouble = Lazy.create(() => {
console.log('Doubling...')
return 21 * 2
})

// Evaluate the Lazy, triggering the computation.
const result1 = lazyDouble.evaluate() // Output: Doubling...
console.log(result1) // Output: 42

// Evaluate the Lazy again, but the computation is not triggered (value is cached).
const result2 = lazyDouble.evaluate()
console.log(result2) // Output: 42

// Map the Lazy to triple the value.
const lazyTriple = lazyDouble.map(value => value * 3)

// Evaluate the new Lazy, triggering the mapped computation.
const result3 = lazyTriple.evaluate() // Output: Doubling...
console.log(result3) // Output: 126

// Use async operations
const getUsers = fetch('https://jsonplaceholder.typicode.com/users')
const lazyMailList = lazyFetch(getUsers)
.map(response => response.json())
.map(users => users.map(user => user.email))

const result4 = await lazyMailList.evaluate()

Type Parameters

  • T

    The type of the value.

Constructors

  • Private

    Private constructor to create an instance of Lazy.

    Type Parameters

    • T

    Parameters

    • computation: (() => T | Promise<T>)

      The function representing the lazy computation.

        • (): T | Promise<T>
        • Returns T | Promise<T>

    Returns Lazy<T>

Properties

computation: (() => T | Promise<T>)

The function representing the lazy computation.

Type declaration

    • (): T | Promise<T>
    • Returns T | Promise<T>

evaluated: boolean = false

Flag indicating whether the value has been evaluated.

value?: T | Promise<T>

The computed value, stored after evaluation.

Methods

  • Evaluates and returns the computed value, calculating it only when necessary.

    Returns T | Promise<T>

    The computed value.

  • Maps the computed value to a new value using the provided function.

    Type Parameters

    • R

      The type of the result after applying the function.

    Parameters

    • fn: ((input) => Promise<R>) | ((input) => R)

      The function to apply to the computed value.

    Returns Lazy<R>

    A new instance of Lazy with the transformed value.

  • Alias for evaluate(). Returns the computed value.

    Returns T | Promise<T>

    The computed value.

    Alias

    Lazy#evaluate

  • Static method to create an instance of Lazy.

    Type Parameters

    • T

      The type of the value.

    Parameters

    • computation: (() => T | Promise<T>)

      The function representing the lazy computation.

        • (): T | Promise<T>
        • Returns T | Promise<T>

    Returns Lazy<T>

    An instance of Lazy.

Generated using TypeDoc