Function bindMethodFactoryByName

  • generates a factory function that binds a class-prototype-method (by name) to the passed object S (which should be an instance of the class).

    Type Parameters

    • T extends Record<M, BindableFunction<T, any[], unknown[], any>>
    • M extends PropertyKey
    • A extends any[]
    • R extends any

    Parameters

    • instance: T

      an object containing the the method (typically a prototype object, but it doesn't have to be that)

    • method_name: M

      the name of the method to generate the binding for

    • Rest ...args: A

      partial tuple of the first few arguments that should be passed in by default

    Returns (<S, SB, SR>(thisArg) => ((...args) => SR))

    a function that can bind any object obj: S to the said method

      • <S, SB, SR>(thisArg): ((...args) => SR)
      • Type Parameters

        • S extends Record<M, BindableFunction<T, any[], unknown[], any>>
        • SB extends any[]
        • SR extends any

        Parameters

        • thisArg: S

        Returns ((...args) => SR)

          • (...args): SR
          • Parameters

            • Rest ...args: SB

            Returns SR

    Example

    const bind_map_set = bindMethodFactoryByName(Map.prototype, "set")
    type ID = number
    const graph_edges = new Map<ID, Set<ID>>()
    const set_graph_edge = bind_map_set(graph_edges) // automatic type inference will correctly assign it the type: `(key: number, value: Set<number>) => Map<number, Set<number>>`
    const edges: [ID, ID[]][] = [[1, [1,2,3]], [2, [3,5]], [3, [4, 7]], [4, [4,5]], [5, [7]]]
    for (const [id, adjacent_ids] of edges) { set_graph_edge(id, new Set(adjacent_ids)) }

    example with assigned default arguments

    const bind_queue_delete_bottom_n_elements = bindMethodFactoryByName(Array.prototype, "splice", 0)
    const queue = [1, 2, 3, 4, 5, 6, 9, 9, 9]
    const release_from_queue = bind_queue_delete_bottom_n_elements(queue) // automatic type inference will correctly assign it the type: `(deleteCount: number, ...items: number[]) => number[]`
    while (queue.length > 0) { console.log(release_from_queue(3)) }
    // will print "[1, 2, 3]", then "[4, 5, 6]", then "[9, 9, 9]"

Generated using TypeDoc