函数柯里化

柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术。

例如下面的求和函数

function sum(a, b, c, d, e, f) {
  return a + b + c + d + e + f;
}

// 柯里化后,可以这么调用
let r = currying(sum)(a)(b)(c)(d)(e)(f)

//柯里化函数
const currying = (fn, arr=[]) => {
  let len = fn.length;
  return function(...args){
    let concatValue = [...arr, ...args];
    if(concatValue.length<len){
     return currying(fn, concatValue);// 递归不停的产生函数
    }else{
      fn(...concatValue)
    }
  }
}
我们可以通过函数柯里化,判断变量的类型
  1. 常用的判断类型的方法有四种:

a.typeof 缺点:不能判断对象类型

typeof []==="object"
typeof {} === "object"

b.constructor 可以找到这个变量是通过谁构造出来的

[].constructor === Array
({}).constructor === Object

c.instanceof 判断一个实例是否属于某种类型(判断谁是谁的实例) 原理是__proto__

new String("123") instanceof String

d.Object.prototype.toString.call() 缺陷:不能细分谁是谁的实例

Object.prototype.toString.call()  "[object Undefined]"
Object.prototype.toString.call('')  "[object String]"
Object.prototype.toString.call(1)   "[object Number]"

2.写一个函数,使用上面的判断条件,判断某一个变量是某个类型:

function isType(value, type){
   return Object.prototype.toString.call(value) === `[object ${type}]`
}
// 判断[] 是一个数组
console.log(isType([], 'Array'));

3.改进上面的方法,可以更直观判断

function isType(type){
    return function(value){
        return Object.prototype.toString.call(value) === `[object ${type}]`
    }
}
let isArray = isType('Array')
console.log(isArray('hello'));
console.log(isArray([]));

4.通过一个柯里化函数 实现通用的柯里化方法

const currying = (fn, arr = []) => {
  let len = fn.length;
  return function (...args) {
    let concatValue = [...arr, ...args];
    if (concatValue.length < len) {
      return currying(fn, concatValue); // 递归不停的产生函数
    } else {
      return fn(...concatValue);
    }
  };
};

function isType(type, value) {
  return Object.prototype.toString.call(value) === `[object ${type}]`;
}
let isArray = currying(isType)("Array");
let isString = currying(isType)("String");

console.log(isArray([]));
console.log(isString("123"));

评论

暂无评论