Basic Functional Programming: Currying • From Wikipedia: Currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument. Currying is related to, but not the same as, partial application. const add = x !=> y !=> x + y add(4)(2) !// 6 addFour = add(4) addFour(2) !// 6
Curry in JavaScript • Because of JavaScript’s syntax, the implementation of curry in JS is usually slightly different from the origin definition. import R from 'ramda' !// Lodash implementation is equivalent. const addThreeNumbers = (x, y, z) !=> x + y + z const curriedAddThreeNumbers = R.curry(addThreeNumbers) curriedAddThreeNumbers(1, 2, 3) curriedAddThreeNumbers(1, 2)(3) curriedAddThreeNumbers(1)(2, 3) curriedAddThreeNumbers(1)(2)(3)
Basic Functional Programming: Function Composition • From Wikipedia: Function composition is an act or mechanism to combine simple functions to build more complicated ones. … 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.
• In math: f(x) = 2x+3 g(x) = x^2 h = (g º f)(x) = g(f(x)) = (2x + 3) ^ 2 const f = x !=> 2 * x + 3 const g = x !=> x ^ 2 const h = compose(g, f) h(2) !// 49
Basic Functional Programming: Higher-order Function • From Wikipedia: A function that does at least one of the following: 1. Takes one or more functions as arguments. 2. Returns a function as its result.
Now We Get All The Tools to Have Fun !// map() and filter() are HOFs const map = fun !=> array !=> array.map(fun) const filter = fun !=> array !=> array.filter(fun) const increaseAll = map(x !=> x + 1) const takeEven = filter(x !=> x % 2 !!=== 0) const increaseAllAndTakeEven = compose( takeEven, increaseAll ) increaseAllAndTakeEven([1, 2, 3, 4, 5]) !// [2, 4, 6]
Higher-order Component • A function that does at least one of the following: 1. Takes one or more components as arguments. 2. Returns a component as its result.
• Remember that, in React, functions can also be components (a.k.a. pure functional component).
import * as Rc from 'recompose' !// enhance is a HOC, which is a function accepting !// a component and return a new component with the !// “MyAwesomeButton" display name. const enhance = Rc.setDisplayName('MyAwesomeButton') const MyAwesomeButton = (!!...props) !=> This is awesome!! export default enhance(MyAwesomeButton) setDisplayName( displayName: string ): HigherOrderComponent