Check three types of realization

Common type of validation methods and characteristics

  1. typeof not verify the object array null
  2. instanceof who's who of examples
  3. Not determined Example Object.prototype.toString.call
  4. constructor judge who is currently constructor

Simple implementation checkType

function checkType(type,value){
    return Object.prototype.toString.call(value) === `[object ${type}]`
}
// 使用
let res = checkType('String','123');

The use of higher-order functions to achieve

This function returns a function checkType incoming type and composition of a closure function is passed in another function type

function checkType(type){
    return function(value){
        return Object.prototype.toString.call(value)===`[object ${type}]`
    }
}
// 使用
let isString = checkType('String');
let isNumber = checkType('Number');
console.log(isString('123'));

Currying achieve

  • If you can not think about how to achieve the amount of writing curried function, you can step by step to pass parameters to consider
  • Parameters passed in the early part of, a new function returns, parameter waiting enough time to reach the implementation of the execution condition
// 验证函数
function checkType(type,value){
    return Object.prototype.toString.call(value) === `[object ${type}]`;
}

// 通用柯里化函数
function curring(fn,arr =[]){
    let len = fn.length; // 代表fn需要传入参数的个数
    return function(...args){
        arr = [...arr, ...args];
        if(arr.length < len ){
            // 传入的参数达不到执行条件,递归继续接受参数
            return curring(fn,arr);
        }else{
            return fn(...arr);
        }
    }
}

// 生成验证函数
let util = {};
let types = ['String', 'Number', 'Boolean', 'Null', 'Undefined'];
types.forEach(type => {
    util[`is${type}`] = curring(checkType)(type);
})
console.log(util.isString('hello'))

Curry concept

  • From the structural point of view function is a function to return function, but also higher-order function;
  • Receiving the plurality of parameters into a single parameter accepts it from the action;
  • The sense is to propose a finer function of the core functions;
  • From the point of view of the implementation process is to function parameters collected, waiting for the opportunity to perform the implementation, which is the lazy evaluation.

Closures concept

  • Execution (declaration) This function may not be current at the current scope

Guess you like

Origin www.cnblogs.com/bonly-ge/p/11846231.html