This is the 19th day of my participation in the August More Text Challenge

Higher-order functions

A higher-order function is a function that operates on other functions. In human terms, the type of a function’s argument or return value is a function. Use functions as variables (functions are first-class citizens)

Function as argument

The most common use is the array prototype method, Array.prototype.filter array.prototype.map array.prototype.foreach array.prototype.some array.prototype.reduce. Then there is the infamous callback hell, passing one function as an argument to another to be called as needed

Function as the return value

In data type judgment, it is recommended to use the following methods:

const isString = (obj) = > Object.prototype.toString.call(obj) === '[object String]';
const isArray = (obj) = > Object.prototype.toString.call(obj) === '[object Array]';
Copy the code

But there is a lot of duplicate code that can take advantage of higher-order functions to return a function

const isType = (type) = > (obj) = > {
  return Object.prototype.toString.call(obj) === '[object ' + type + '] ';
};

isType('String') ('123'); // true
isType('Array') ([1.2.3]); // true
Copy the code

Similarly, when dealing with DOM events, you might want to pass some parameters, and you can also take advantage of higher-order functions

// react
function Component(){
	const handleClick = (param) = >(event) = >{... }return <button onClick=(handleClick(param))>click</button>
}
Copy the code

When the click event is fired, it is actually the function that called handleClick() after execution. Of course, it can also be implemented using lazy functions

In addition, the feature of using higher-order functions to return a new function is also used for stabilization and throttling

To a topic

Array flattening and de-weighting

Array.prototype.myFlat = function () {
  return[].concat(... this.map((item) = > (Array.isArray(item) ? item.myFlat() : item)));
};

Array.prototype.unique = function () {
  return [...new Set(this)];
};

var old_arr = [[1.2.2], [3.4.5.5], [6.7.8.9[11.12[12.13[14]]]], 10];
console.log(
  old_arr
    .myFlat()
    .unique()
    .sort((a, b) = > a - b)
);
Copy the code

The function is currified

The goal is to preserve the parameters of the function and execute the function when the number of parameters reaches a certain number

const curry = (fn) = > (fn1 = (. args) = >(args.length >= fn.length ? fn(... args) :(. arg) = >fn1(... args, ... arg)));Copy the code

conclusion

A higher-order function is a function passed as an argument to another function or a function returned as a result of another function. The advantage of functions as arguments is that they are more flexible, and you don’t need to consider how the inside of a function is implemented when calling it.