Skip to content

Compose

A composition of functions, each function is given the next function as an argument and must call it to continue executing.

๐ŸŽฌ Usage

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

    const zero = (fn) => () => fn(0)

    const size = (fn) => (num) => fn({ num })

    const increment =
                (fn) =>
    ({ num }) =>
    fn({ num: num + 1 })

    const args = (arg) => (args) => args[arg]

    const composed = compose(zero, size, increment, increment, args("num"))

    const decomposed = zero(size(increment(increment(args("num")))))

    const expected = decomposed()

    const result = composed()
</script>

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

<h1> Expected: {expected}</h1>

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

๐Ÿ‘ป Arguments

Name Description Type Required
fn The function to compose Fn[] yes

โ†ฉ๏ธ Returns

A composed function.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
export type Fn<TArgs = any, KReturn = any | void> = (
    ...args: TArgs[]
) => KReturn

/**
 * a composition of functions, each function is given the next function as an argument and must call it to continue executing.
 *
 * @param fn - the function to compose
 *
 * @returns the composed function
 */
export function compose(...fn: Fn[]) {
    return fn.reverse().reduce((acc, _fn) => _fn(acc))
}

Last update: 2023-02-14