0%

高阶函数

高阶函数模板

1
2
3
4
5
function HoF0(fn){
return function(...args){
return fn.apply(this,args);
}
}

Once

1
2
3
4
5
6
7
8
9
function once(fn){
return function(..args){
if(fn){
const ret=fn.apply(this,args);
fn=null;
return ret;
}
}
}

Throttle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function throttle(fn,time=500){
let timer;
return function(...args){
if(timer==null){
fn.apply(this.args);
timer=setTimeout(()=>{
timer=null;
},time)
}
}

}
btn.onclick=throttle(function(e){
circle.innerHTML=parseInt(circle.innerHTML)+1;
circle.className='fade';
setTimeout(()=>circle.className='',250);
});

Debouce

1
2
3
4
5
6
7
8
9
10
11
12
function debouce(fn,dur){
dur=dur||100;
var timer;
return function(){
clearTimeout(timer);
timer=setTimeOut(()=>{
fn.apply(this,arguments);
},dur);
}


}

iterative

1
2
3
4
5
6
7
8
9
10
11
12
13
function iterative(fn){
return function(subject,...rest){
if(isIterable(subject)){
const ret=[];
for(let obj of subject){
ret.push(fn.apply(this,[obj,...rest]));
}
return ret;
}
return fn.apply(this,[subject,...rest]);
}
}

过程抽象

HOF

装饰器

命令式/声明式

洗牌算法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function*draw(cards){
const c=[...cards];
for(let i=c.length;i>0;i--){
const pIdx=Math.floor(Math.random()*i);
[c[pIdx],c[i-1]]=[c[i-1],c[pIdx]];
yield c[i-1];
}
}
function generate(amount,count){
if(count<=1)return [amount];
const cards=Array(amount-1).fill(0).map((_,i)=>i+1);
const pick=draw(cards);
for(let i=0;i<count;i++){
result.push(pick.next().value);
}
result.sort((a,b)=>a-b);
for(let i=count-1;i>0;i--){
result[i]=result[i]-result[i-1];
}
return result;
}