const isType =(type: string) => (value: any) => typeof(value) === type;
what?
在理解双箭头函数之前能够先理解一下函数式编程中的一个概念:
柯里化:把一个多参数函数转化成一个嵌套的一元函数(只有一个参数的函数)的过程。
可见双箭头函数就是一个多参数函数的柯里化版本。
转化成JavaScript后:
const isType = function (type){ return function (value) { return typeof(value) === type; } }
(这样看就有点闭包的意思了,也能够了解为把其中的每一步骤进行封装,保留每一步的后果,作为下一步开始的条件)
你也能够写成没有柯里化的函数也是能够的:
const isType = function (type,value){ return typeof(value) === type; }
它的调用办法:
isType (“string”)
//返回一个函数:function (value) {return typeOf(value) === type;}isType (“string”)(“abc”
) //返回:trueconst type = isType("string"); type("abc");
//返回:true
Why?
那问题来了,为什么要柯里化呢?它有什么用?
可读性: isType (“string”)(“abc”)
可复用性 :重复使用const type = isType(“string”); 用来做其余判断type (“def”);
可维护性 :
const fn = (a,b) => a * b; //可批改成a+bconst isType =(fn)=> (type) => (value) =>fn(type,value);console.log(isType (fn)(2)); //返回函数 console.log(isType (fn)(2)(3)); //6const type = isType(fn)(2); console.log(type(4)); //8
How?
应用场景
日志:
const curry = (fn) => { if(typeof fn != 'function'){ throw Error('NO function provided'); } return function curriedFn(...args){ if(args.length < fn.length){ return function(){ return curriedFn.apply(null,args.concat([].slice.call(arguments))); }; } return fn.apply(null,args); }; };err("ERROR","Error At Stats.js","text1",22);err("ERROR","Error At Stats.js","text2",23);const error = curry(err)("ERROR")("Error At Stats.js");error ("text1")(22);error ("text2")(23);
- 在数组内容中查找数字
const curry = (binaryFn) => { return function (firstArg) { return function (secondArg) { return binaryFn(firstArg,secondArg); }; }; };
let match = curry(function(expr, str) { rerurn str.match(expr);};let hasNumber = match(/[0-9]+/);let filter = curry(function(f,ary){ return ary.filter(f);};let findNumbersInArray = filter(hasNumber);findNumbersInArray(["js","number1"]); //["number1"]
- 求数组的平方
let map = curry(function(f,ary){ return ary.map(f); )}; let squareAll = map((x) => x*x); squareAll([1,2,3]); //[1,4,9]