写一些常见的手写题,总结一下,顺便复习一下,太久不写就算以前再怎么清楚,后面也会一脸懵逼
- compose函数:组合函数,将函数串联起来执行,前一个函数的输出值是后一个函数的输入值
function compose(...fn){
return function(val){
let last=fn[0](val);
for(let i=1;i<fn.length;i++){
last=fn[i](last);
}
return last
}
}
- settimeout 模拟实现 setinterval 以及 setinterval 模拟实现 settimeout
function settimeout(fn, time) {
let timer = setInterval(() => {
fn();
clearInterval(timer)
}, time)
}
function setInterval(fn, time) {
function interval(fn, time) {
setTimeout(() => {
fn()
interval(fn,time);
}, time)
}
interval(fn,time)
}
- js发布订阅者模式 eventbus就是这个原理
function eventbus(){
this.center=[];
function on(eventname,callback){
this.center[eventname]=this.center[eventname]||[];
this.center[eventname].push(callback)
}
function emit(eventname,...args){
this.center[eventname].foreach((item)=>{item(args)});
}
}
- 数组扁平化
function myflat(arr){
let array=[];
for(let item of arr){
if(Array.isArray(item){
array=array.concat(myflat(item))
}else{
array.push(item)
}
}
return array;
}
- 寄生组合继承:
function parent(){
this.name='father';
}
parent.prototype.say=function(){
console.log('我是你爹');
}
function son(...args){
parent.call(this,args);
}
son.prototype=Object.create(parent.prototype);
son.prototype.constructor=son;
- promise并行调度器
class scheduler{
constructor(n){
this.queue=[];
this.runcount=0;
this.maxcount=n;
}
add(fn,time){
const promisecretor=()=>{
return new promise((resolve,reject)+>{
setTimeout(()=>{
fn();
resolve();
},time)
})
}
this.queue.push(promisecretor(fn,time))
}
taskstart(){
for(let i=0;i<maxcount;i++){
this.request()
}
}
request(){
if (!this.queue || !this.queue.length || this.runCounts >= this.maxCount){
return;
}
this.runCounts++;
this.queue .shift()() .then(() => {
this.runCounts--;
this.request();
});
}
}
- 手写new 感觉寄生组合继承很像,拷贝对象然后call
function mynew(fn,...args){
let obj=Object.create(fn.prototype);
return fn.call(obj,args)
}
- 手写bind、call、apply
function Myapply(context=window,..args){
let fn=symbol();
return context[fn](args);
}
Function.prototype.mybind(context=window,...args){
fn=this;
return function(...arguements){
fn.apply(this instanceof fn?this:context,[...args,...arguements])
}
}