手写代码
数组扁平化
function flat(arr){
let res = []
for(let item of arr){
if(item instanceof Array){
res.push(...flat(item))
}
else{
res.push(item)
}
}
return res
}
演示原型链
function A(){
}
let a = new A()
a.__proto__ == A.prototype
Object.getPrototypeOf(a) == A.prototype
a.constructor == A
A.prototype.constructor == A
true == a instanceof A
typeof a == 'object'
new运算符
function myNew(constructor,...args) {
let res = {}
Object.setPrototypeOf(res,constructor.prototype)
let outcome = constructor.call(res,...args)
if(outcome instanceof Object) return outcome
return res
}
函数柯里化
function Curry_1(fn){
return function curried(...args){
if(args.length >= fn.length){
return fn.apply(this,args)
}
return function(...restArgs){
return curried.apply(this,args.concat(restArgs))
}
}
}
function Curry_2(fn){
let args = []
return function curried() {
if(arguments.length !== 0){
args.push(...arguments)
return curried
}
return fn.apply(this,args)
}
}
function sum(){
return [...arguments].reduce((pre,cur) => pre + cur)
}
const curriedSum = Curry_2(sum)
let res = curriedSum(1)(2)(3)()
console.log(res)
可以判断所有类型的函数(包括引用类型)
function myTypeof(obj){
return Object.prototype.toString.call(obj).slice(8,-1)
}
instanceof运算符
function myInstanceof(left,right){
let proto = Object.getPrototypeOf(left)
while(proto){
if(proto == right.prototype) return true
proto = Object.getPrototypeOf(proto)
}
return false
}
深拷贝函数(并非最完善版本)
function deepCopy(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(item => deepCopy(item));
}
const result = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepCopy(obj[key]);
}
}
return result;
}
节流函数(delay时间内,仅执行第一次)
function throttle(fn, delay) {
let curTime = 0;
return function(...args) {
const now = Date.now();
if (now - curTime >= delay) {
curTime = now;
fn.apply(this, args);
}
};
}
防抖函数(每次触发重新计时delay时长)
function debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}