function after(times,cb){
return function(){
if(--times==0){
cb()
}
}
}
let fn = after(3,function(){
console.log('達到三次了')
})
fn()
fn()
fn()
複製代碼
函數柯里化就是能夠把一個函數的執行須要傳遞的參數分屢次執行node
// 通用的柯里化
const add = (a, b, c, d, e) => {
return a + b + c + d + e;
};
const curring = (fn,arr = [])=>{
let len = fn.length
return (...args)=>{
arr = arr.concat(args); // [1] [1,2,3] < 5
if(arr.length < len){
return curring(fn,arr)
}
return fn(...arr)
}
}
let r = curring(add)(1)(2)(3)(4); // [1,2,3,4,5]
複製代碼
簡單使用判斷數據類型
編程
const checkType = (type, content) => {
return Object.prototype.toString.call(content) === `[object ${type}]`;
};
let types = ["Number", "String", "Boolean"];
let utils = {};
types.forEach(type => {
utils["is" + type] = curring(checkType)(type); // 先傳入一個參數
});
console.log(utils.isString('hello'));
複製代碼
須要name和age都獲取到而後輸出。bash
let fs = require('fs')
let schoolInfo = {}
function after(times,cb){
return function(){
if(--times==0){
cb()
}
}
}
let fn = after(2,function(){
consolr.log(schoolInfo)
})
fs.readFile('./name.txt','utf8',function(err,data){
schoolInfo['name'] = data;
fn()
})
fs.readFile('./age.txt','utf8',function(err,data){
schoolInfo['age'] = data;
fn()
})
複製代碼
let dep = {
arr:[],
emit(){
this.arr.forEach(fn=>fn())
}
on(fn){
this.arr.push(fn)
}
}
dep.on(function(){
if(Object.keys(schoolInfo).length===2){
console.log(schoolInfo)
}
})
fs.readFile('./name.txt','utf8',function(err,data){
schoolInfo['name'] = data;
dep.emit()
})
fs.readFile('./age.txt','utf8',function(err,data){
schoolInfo['age'] = data;
dep.emit()
})
複製代碼