Functional Programming
· 2 min read
参考:
// 面向过程const a = 1;const b = 2;const c = a + b;
// OOPclass Sum(){ add(a, b) { return a+b; }}const instance = new Sum();instance.add(1,3)
// 函数式编程function add(a,b){ return a+b;}add(1,2)
函数不是指function
,而是数学上的映射关系
y = f(x)
#
高阶函数函数作为参数和返回值
#
纯函数- same input same output
- 执行过程没有副作用
cache
let _ = require("lodash");
function add(a, b) { console.log('begin') return a + b;}const resolver = (...args) =>JSON.stringify(args);
// function memoize(func,resolver){// let cache ={}// return (...args) =>{// const key = resolver(...args)// if(cache[key]){// return check[key]// }else{// return (check[key] = func(...args))// }// }// }
const memoizeAdd = .memoize(add,resolver);console.log(memoizeAdd(1,2))console.log(memoizeAdd(1,2))console.log(memoizeAdd(1,2))
test
#
Currylet _ = require("lodash");function add(a, b, c) { console.log("begin"); return a + b + c;}
// function curry(func) {// const argsLength = func.length;// let curried = (...args) => {// if (args.length < argsLength) {// return (...rest) => curried(...args, ...rest);// }// return func(...args);// };// return curried;// }
let curriedAdd = _.curry(add);console.log(curriedAdd(1, 2, 3));console.log(curriedAdd(1)(2, 3));console.log(curriedAdd(1)(2)(3));
#
组合let _ = require("lodash");
let str = "a";function add1(str) { return str + 1;}function add2(str) { return str + 2;}function add3(str) { return str + 3;}
function flow(...fns) { if (fns.length === 1) return fns[0]; return fns.reduce( (a, b) => (...args) => a(b(...args)) );}
// let r1 = add3(add2(add1(str)));let flowed = _.flow(add3, add2, add1);let r1 = flowed("a"); // a321
#
函子#
PointFree把数据处理的过程先定义成一种与参数无关的合成运算
const { compose } = require("lodash/fp");let money = 500;money -= 100;money -= 100;
// PointFreefunction buyHouse(money) { return money - 100;}function buyCar(money) { return money - 100;}
let fn = compose(buyCar, buyHouse);fn(500);