Function composition

Compose: only cares about the 3 small functions and the input, not the intermediate result

fn = compose(f1, f2, f3)
b = fn(a)

// combine functions
const reverse = arr= > arr.reverse()
const first = arr= > arr[0]
const toUpper = str= > str.toUpperCase()

const f = compose(toUpper, first, reverse)
function compose(. args) {
    return function(value) {
        return args.reverse().reduce(function(total, func) {
            return func(total)
        },value)
    }
}

console.log(f(['askj'.'rose'.'jack']))

// Pointfree
// world hello you => W. H. Y.
const firstLetterToUpper = fp.flowRight(fp.join('. '), fp.map(fp.flowRight(fp.toUpper, fp.first)) ,fp.split(' '))
console.log(firstLetterToUpper('world hello you'))
Copy the code

Objective: To maximize function reuse

functor

Functors control side effects, handle function exceptions, asynchronous operations, and so on

  • The operations of functional programming do not operate directly on values, but are performed by functors
  • A functor is an object that implements the Map contract
  • We can think of a functor as a box that encapsulates a value
  • To process the values in the box, we need to pass a value-handling function (pure function) to the box’s Map method, which will process the values
  • The final map method returns a box containing the new value (functor)
/ / functor
 class Container {
    static of (value) {
       return new Container(value)
    }

     constructor (value) {
        this._value = value
     }

     map (fn) {
        return Container.of(fn(this._value))
     }
 }

 let r = Container.of(5)
            .map(x= > x + 2)
            .map(x= > x * x)

 console.log(r)
Copy the code