The composition
Function Composition
In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole. -- Wikipedia
Example:
1 | var compose = (f, g) => (x) => f(g(x)) |
In the definition of compose, g will be executed before f, thus creating a right-to-left data stream. This is much more readable than nesting a bunch of function calls.
Associativity
Like many other functional programming concepts, associativity is derived from math.It is an expression in which the order of evaluation does not affect the end result provided the sequence of the operands does not get changed. -- JOSEPH REX
Example:
1 | 2 + (3 + 4) === 2 + 3 + 4 // true |
Because of the grouping of calls to compose is not important, so the result is the same. This also gives us the ability to write a variadic compose.
Like this:
1 | var last = compose(head, reverse) |
There is no standard answer on how to composition, just make it more reusable.
The Currying
What is currying
Currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. -- Wikipedia
It mean this:
1 | let add = (x) => (y) => x + y |
In order to define functions more easily, we need the loadsh, it will help us to currying the function.
make some using thing
1 | var _ = require("loadsh").curry |
TikTok svg
Transducer
Reducer
Reducer 將多個 input fold 成一個 output.
1 | const add = (a, b) => a + b |
Transducer
Transducer 做的事情大致相同,但是與普通的 reducer 不同的是,它可以通過多個 function 組合而成.而普通的 reducer 不能組合,因爲他們接受兩個參數,但是只返回一個值,所以不能將這次的結果傳入下一個 reducer:
1 | // reducer |