函数柯里化

柯里化(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"));

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理