JavaScript higher-order functions

personal blog

What is the higher-order functions

"Javascript design patterns and development practice" in the definition function can be passed as parameters, it can be output as a return value

The following conditions:

  1. Accepting as input one or more functions
  2. The output of a function

Higher-order functions are those functions typically include more than type functions. In functional programming, higher order function returns another function is called of Curry.

As a function of transmission parameters

A function as an argument, we can draw part of easily changed to business logic, which can separate business code changed and unchanged portions

Callback:

The transfer function into a method, a function is not performed immediately, after waiting out the execution result.

let func = function (callback){
    if(n === 'owen'){
        callback() //回调函数
    }
}
 function say (){
     console.log('Hello Word')
 }
 func(say)

Array object commonly used method

[1,2,3,4].forEach(iteration)
 function iteration(v){
     console.log(v)
 }

Output as a return value

Let function continues to return an executable function, which means the continuation of the process is running.

Analyzing Data Type

let type = type =>{
    return obj => Object.prototype.toString.call(obj) === `[object ${type}]`
}
let isArray = type('Array'),isString = type('String'),isNumber = type('Number'),isObject = type('Object');

// or
let Type = (function(){
    let type = {},types = ['Object','Array','Number','String']
    for (let val of  types) {
        (function(str){
            type[`is${str}`] = (obj) => Object.prototype.toString.call( obj ) === `[object ${str}]`
        }(val))
    }
    console.log(type)
    return type
}())
Type.isNumber(2) // true

Achieve the AOP (the slice-oriented programming)

By way of AOP pre-compiler and run-time dynamic agent technology to implement a unified program functions maintenance.
JAVA language AOP some business logic has nothing to do with the core functions pulled out, usually including log statistics, security control, exception handling lamp. Through the "dynamic weaving" means incorporated into the business logic.
Benefits: it can be kept clean and highly cohesive business logic modules to facilitate the reuse log statistics and other functional modules.

AOP is implemented in JavaScript refers to a function of "the weaving" into another function
embodied:

Function.prototype.before = function(beforeFn){
    let that = this; // 谁调用指向谁 下面是由 func 函数调用所以是指向 func

    return function( ...args){
        beforeFn.apply(this,args) // 执行回调函数 beforeFn
        return that.apply(this,args) // 执行原函数
    }
}

Function.prototype.after = function(afterFn){
    let that = this; // 谁调用指向谁 下面是由befor函数调用所以是指向 befor
    return function( ...args){
        let ret = that.apply(this,args) // 执行并接收原对象
        afterFn.apply(this,args) //  执行回调函数 beforeFn
        return ret
    }
}
var func = function (){
    console.log(2)
}
func = func.before(function (){
    console.log(1)
}).after(function (){
    console.log(3)
})
func()
// 1 2 3

Currying function (function currying)

In mathematics and computer science, currying function is to convert into a series of a plurality of parameters using a parameter of the function, and returns the new function that takes the remaining parameters

curring known as partial evaluation; curring function first receives a number of parameters, and the function is not evaluated immediately, but continue to return another function, while a newly incoming parameters are stored in a closure formed to be function when the real value of the request, before it will be disposable for parameters evaluated

A simple example:

function add(a,b) {
    return a + b
}
add(1,2) // 3

// 如果柯里化
add(1)(2) // 3

Then use currying to achieve a function of the sum of consumption within a few days

// 普通方法
var cost = (function() {
    var args = [];
    return function(){
        if(!arguments.length){
            let money = 0
            for (let val of args ){
                money += val;
            }
            return money
        }else{
            [].push.apply(args,arguments)
        }
    }
})()
cost(100);
cost(100);
cost(100);
cost(); // 300

cost(100)(100)(100)

// currying
/**
 * 保存原函数参数返回到新函数中使用
 */

//  func(100,100,100) //300
function count (...args){
    let num = 0;
     if(args.length>1){
         for (let v of args){
             num +=v
         }
         return num
     }else{
         return args[0]
     }
}

var  curry = function(func){
        let args = []
    return function fn(...Args){
        if (Args.length){
            [].push.apply(args,Args)
            return fn
        }else{
            return func.apply(this,args)
        }
    }
}
cost = curry(count);

cost(100);
cost(100);
cost(100);
cost(); // 300

Throttle function

JavaScript in most cases the user actively starting function, the function itself to achieve unless unreasonable, or generally do not experience problems with performance-related, in a few cases, the control function is not triggered directly by the user, may be invoked frequently cause serious performance issues.
such as:

window.addEventListener('resize', function(e) {
   // do something...
});
window.addEventListener('scroll', function(e) {
   // do something...
});
Dom.addEventListener('mousemove', function(e) {
   // do something...
});

// progress
xhr.upload.addEventListener("progress", function(result) {
    // do something...
}, false);

// ...

1 second to trigger these events many times, and often manipulate the DOM node, so the performance loss, the browser will be too much and therefore Caton; we do not need the actual trigger such high frequencies so some of us can ignore the number of executions over a period of time

Throttling principle:

If the event to keep firing can be performed only once every so often.

Use a timer throttling

Function to be executed with setTimeouta time delay function is executed, if the timer is not complete execution of the function to be executed took down are ignored.

 function throttle(func,wait) {
      let timer, firstFlag = true; //第一次立即执行
      return function(...args) {
          if(timer)  return false; // 如果存在定时器这不执行

          let that = this;
          if(firstFlag){
              firstFlag = false;
             return func.apply(that,args);
          }
          timer = setTimeout(function(){
               clearTimeout(timer);
               timer = null;
               func.apply(that,args);
            },wait)
      }
 }
 window.addEventListener('scroll', throttle(function(e) {
  console.log(e) 
},1000));

Anti-shake function

And throttle certain period of time once the event handler is called only different functions, image stabilization is no longer certain period of time a trigger event, the event handler will be executed once, if before the set time comes, once again triggered the event, it restart delay. (Users no longer trigger the corresponding event before the implementation of an event)

function debounce(func,wait) {
    let timer;
    return function(...args) {
        let that = this;
        clearTimeout(timer);
        timer = setTimeout(function(){
            func.apply(that,args)
        },wait)
    }
}
 window.addEventListener('scroll', debounce(function(e) {
  console.log(e) 
},1000));

Guess you like

Origin www.cnblogs.com/gaoguowen/p/11223358.html