Skip to content

Chain

A function that takes a list of functions and executes them in order.

๐ŸŽฌ Usage

<script>
    import {chain} from "@sveu/shared/curry"

    let result = ""

    const chained = chain(
        (a, b) => a + b,
        (a) => a * 2
    )
</script>

<h1>Result: {result}</h1>

<button on:click={() => result = chained(7, 7)}>Sum</button>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
funcs The list of functions to execute FunctionArgs[] yes

โ†ฉ๏ธ Returns

A chained function that takes the same arguments as the first function in the list.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import type { FunctionArgs } from "../../utils"

/**
 * A function that takes a list of functions and executes them in order.
 *
 * @param funcs - The list of functions to execute.
 *
 */
export function chain(...funcs: FunctionArgs[]) {
    return (...args: any[]) => {
        return funcs.slice(1).reduce((acc, fn) => fn(acc), funcs[0](...args))
    }
}

Last update: 2023-02-14