Immerse_001
2023-04-22 11:12:52浏览 1841
面试必考: 手撕代码系列(一)
手写深拷贝 (deepClone)
const deepClone = source => {
const obj = {};
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (Object.prototype.toString.call(source[key]).slice(8, -1) === 'Object') {
obj[key] = deepClone(source[key]);
} else {
obj[key] = source[key];
}
}
}
return obj;
};
const a = {
age: 12,
otherInfo: {
sex: 0,
},
};
const b = deepClone(a);
b.age = 22;
b.otherInfo.sex = 1;
console.log('a------>', a);
console.log('b------>', b);
手写浅拷贝 (shallowClone)
const shallowClone = source => {
const obj = {};
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
obj[key] = source[key];
}
}
return obj;
};
const a = {
age: 12,
otherInfo: {
sex: 0,
},
};
const b = shallowClone(a);
b.age = 22;
b.otherInfo.sex = 1;
console.log('a------>', a);
console.log('b------>', b);
手写 new 操作符 (customNew)
const customNew = (fn, ...rest) => {
const obj = {};
obj.__proto__ = fn.prototype;
const res = fn.apply(obj, rest);
return Object.prototype.toString.call(res).slice(8, -1) === 'Object' ? res : obj;
};
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.getName = function () {
return this.name;
};
const person = customNew(Person, 'John', 11);
console.log('person ------->', person);
console.log('person.getName() ------->', person.getName());
手写节流 (throttle)
const throttle = (fn, time = 1500) => {
let flag = null;
return function () {
if (flag) return;
flag = true;
fn();
let timer = setTimeout(() => {
flag = false;
clearTimeout(timer);
}, time);
};
};
手写防抖 (debounce)
const debounce = (fn, time = 1500) => {
let timer = null;
return function () {
timer && clearTimeout(timer);
timer = setTimeout(() => {
fn();
}, time);
}
};
特殊字符描述:
- 问题标注
Q:(question)
- 答案标注
R:(result)
- 注意事项标准:
A:(attention matters)
- 详情描述标注:
D:(detail info)
- 总结标注:
S:(summary)
- 分析标注:
Ana:(analysis)
- 提示标注:
T:(tips)