Functional programming

What is functional programming

Functional programming is a programming paradigm.

  • Process oriented development
const a = 1
const b = 2
const result = a + b
Copy the code
Class Calculator {add(a,b) {return a+b}} const c = new Calculator() c.addd (1,2)Copy the code
function add(a,b) {
  return a+b
}
return a+b
Copy the code
  • Object-oriented programming
class Calculator {
	add(a,b) {
		return a+b
	}
}
const c = new Calculator()
c.add(1.2)
Copy the code
  • Function-oriented development
function add(a,b) {
  return a+b
}
return a+b
Copy the code

Analysis lodash

The lodash memoize

- Take a look at the following function, which executes the same 'add' call three times. So the add function actually executes the same entry three times. ``` function add(a, b) { return a + b; } console.log(add(1,2)) console.log(add(1,2)) console.log(add(1,2))) memoize in ' '-' 'lodash' That is, input parameters' 1,2 'of the pure function' add 'are cached in' memoize '. The input parameter is cached, and when the input parameter matches the previous one, the result of the previous record is directly fetched. ``` const _ = require('lodash'); function add(a, b) { return a + b; } const memoizeAdd = _.memoize(add); Log (memoizeAdd(1,2)) console.log(memoizeAdd(1,2)) console.log(memoizeAdd(1,2)) ' '- implement a simple version of my own' memoize 'method The idea is to return a function that uses the closure properties to hold a map in the 'memoize' function. Log each input parameter to return a function with the same input parameter. ``` function add(a, b) { return a + b; } function memoize(fn) { const map = new Map(); return (... args) => { const key = JSON.stringify(args.sort((a, b) => a - b)); const memoized = map.get(key); if (! memoized) { const value = fn(... args); map.set(key, value); return value; } return memoized; }; } const memoizeAdd = memoize(add); // the add(1,2) function is executed only once, the rest of the time the value is cached. console.log(memoizeAdd(1, 2)); console.log(memoizeAdd(1, 2)); console.log(memoizeAdd(1, 2)); ` ` `Copy the code

The lodash function curries

Var ABC = function(a, b, c) {return [a, b, c]; }; var curried = _.curry(abc); curried(1)(2)(3); // => [1, 2, 3] curried(1, 2)(3); // => [1, 2, 3] curried(1, 2, 3); Args function curry(fn) {return function _curry(... args) { if (args.length === fn.length) { return fn(... args); } return function (... rest) { const params = [].concat(args, rest); return _curry(... params); }; }; } ` ` `Copy the code

Lodash Flow function composition function

const _ = require('lodash'); function square(n) { return n * n; } function add(a) { return a + 3; Var addSquare = flow([square, add]); // => 9 function flow(fns) { return (arg) => { return fns.reduce((pre, cur) => { return cur(pre); }, arg); }; } console.log(addSquare(2));Copy the code