高阶函数
大约 1 分钟
高阶函数
- 一个函数返回一个函数
- 一个函数的参数是一个函数
function a() {
return function () {};
}
function b(callback) {
callback();
}
切片编程
高阶函数可以对原有的函数进行扩展 切片增加额外的逻辑,在原有逻辑中增添额外的逻辑
function core(a, b, c) {
console.log('核心逻辑');
console.log(a, b, c);
}
core.before = function (fn) {
return (...args) => {
fn();
this(...args);
};
};
const newCore = core.before(() => {
console.log('我添加的逻辑');
});
newCore(1, 2, 3);
函数柯理化
- 把一个函数拆分为多个“小”函数,每一个函数的参数只有一个
- 偏函数,参数可以不是一个的柯理化函数,正常来编写代码,偏函数也称之为柯理化
function sum(a, b, c) {
return a + b + c;
}
function curry(func) {
const curried = (...args) => {
if (args.length < func.length) {
return (...others) => curried(...args, ...others);
} else {
return func(...args);
}
};
return curried;
}
let curriedSum = curry(sum);
console.log(curriedSum(1)(2)(3));
异步逻辑
同步【阻塞】,异步【非阻塞】
const person = {};
function after(times, callback) {
return function () {
if (--times === 0) {
callback();
}
};
}
const out = after(2, function () {
console.log(person);
});
fs.readFile(path.resolve(__dirname, 'name.txt'), 'utf-8', function (err, data) {
person.name = data;
out();
});
fs.readFile(path.resolve(__dirname, 'age.txt'), 'utf-8', function (err, data) {
person.age = data;
out();
});
发布-订阅模式
发布-订阅模式其实是一种对象间一对多的依赖关系,当一个对象的状态发送改变时,所有依赖于它的对象都将得到状态改变的通知。
const event = {
_arr: [],
// 把函数存起来
on(callback) {
this._arr.push(callback);
},
// 将函数拿出来执行
emit(...ages) {
this._arr.forEach((fn) => fn(...ages));
},
};
event.on(function () {
console.log('读取一次');
});
event.emit;
fs.readFile(path.resolve(__dirname, 'name.txt'), 'utf-8', function (err, data) {
event.emit();
});