compose
题目描述:实现一个 compose 函数
function fn1(x) {
return x + 1;
}
function fn2(x) {
return x + 2;
}
function fn3(x) {
return x + 3;
}
function fn4(x) {
return x + 4;
}
function myCompost(...fn){
if(fn.length === 0){
return (v) => v
}
else if(fn.length === 1){
return fn[0]
}
return fn.reduce((a,b)=>(...args)=>a(b(...args)))
}
const a = myCompost(fn1, fn2, fn3, fn4);
console.log(a(1)); // 1+4+3+2+1=11
settimeout 模拟实现 setinterval
setInterval 有两个缺点:
使用 setInterval 时,某些间隔会被跳过;
可能多个定时器会连续执行;
可以这么理解:每个 setTimeout 产生的任务会直接 push 到任务队列中;而 setInterval 在每次把任务 push 到任务队列前,都要进行一下判断(看上次的任务是否仍在队列中,如果有则不添加,没有则添加)。参考
function mySetinterval(fn,delay){
let timer = null
function interval(){
fn()
timer = setTimeout(interval,delay)
}
interval()
return {
cancel:()=>clearTimeout(timer)
}
}
let a = mySetinterval(()=>{
console.log(1);
},1000)
setTimeout(()=>{
a.cancel()
},3000)
发布订阅模式
题目描述:实现一个发布订阅模式拥有 on emit once off 方法
class EventEmitter {
constructor() {
this.event = {}
}
on(type, callback) {
if (!this.event[type]) {
this.event[type] = [callback]
} else {
this.event[type].push(callback)
}
}
off(type, callback) {
if (!this.event[type]) return
this.event[type] = this.event[type].filter(item => item != callback)
}
once(type, callback) {
let fn = () => {
callback()
this.off(type,fn)
}
this.on(type, fn)
}
emit(type, ...rest) {
if (!this.event[type]) return
this.event[type].forEach((fn) => fn.apply(this, rest));
}
}
// 使用如下
const myEvent = new EventEmitter();
const handle = (...rest) => {
console.log(rest);
};
myEvent.on("click", handle);
myEvent.emit("click", 1, 2, 3, 4);
myEvent.off("click", handle);
myEvent.emit("click", 1, 2);
myEvent.once("dbClick", () => {
console.log(123456);
});
myEvent.emit("dbClick");
myEvent.emit("dbClick");
数组去重
function uniqueArr(arr){
return [...new Set(arr)]
}
数组扁平化
题目描述:实现一个方法使多维数组变成一维数组
递归版本
function flatter(arr) {
if (!arr.length) return;
return arr.reduce(
(pre, cur) =>
Array.isArray(cur) ? [...pre, ...flatter(cur)] : [...pre, cur],
[]
);
}
// console.log(flatter([1, 2, [1, [2, 3, [4, 5, [6]]]]]));
迭代版本
function flatter(arr) {
if (!arr.length) return;
while (arr.some((item) => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
寄生组合继承
function Parent(name) {
this.name = name;
this.say = () => {
console.log(111);
};
}
Parent.prototype.play = () => {
console.log(222);
};
function Children(name) {
Parent.call(this);
this.name = name;
}
Children.prototype = Object.create(Parent.prototype);
Children.prototype.constructor = Children;
let child = new Children("111");
console.log(child.name);
child.say();
child.play();