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
Authors: Mohamed-Kaizen