一、cloneDeep
const { cloneDeep } = _
const obj = {
name: 'xx',
arr: [1, 2, 3, [4, 5]],
person: { name: 'yy' }
}
const obj1 = cloneDeep(obj)
手动实现:
function cloneDeep(val) {
if (val === null || typeof val !== 'object') return val
var res = new val.constructor()
for (var key in val) res[key] = cloneDeep(val[key]) // 递归调用
return res
}
这里没有对Set、Map、RegExp和循环引用做处理。另外,可以使用structuredClone进行深复制,这是一个比较新的全局方法
二、debounce
var { debounce } = _
window.addEventListener('resize', debounce(handle, 200))
function handle() {
console.log(document.documentElement.clientWidth)
}
实现:
function debounce(cb, delay) {
var timer = null
return function () {
if (timer) clearTimeout(timer)
var _this = this
var _arguments = arguments
timer = setTimeout(function () {
cb.apply(_this, _arguments)
}, delay)
}
}
三、throttle
var { throttle } = _
window.addEventListener('resize', throttle(handle, 200))
function handle() {
console.log(document.documentElement.clientWidth)
}
通过定时器实现:
function mythrottle(cb, delay) {
var timer = null
return function () {
var _this = this
var _arguments = arguments
if (!timer) {
timer = setTimeout(function () {
cb.apply(_this, _arguments)
clearTimeout(timer)
timer = null
}, delay)
}
}
}
通过时间戳实现:
function throttle(cb, delay) {
var prevTime = Date.now()
return function () {
var curTime = Date.now()
if (curTime - prevTime > delay) {
cb.apply(this, arguments)
prevTime = Date.now()
}
}
}
四、curry
var { curry } = _
function sum(a, b, c) {
return a + b + c
}
const currySum = curry(sum)
console.log(currySum(1, 2, 3))
console.log(currySum(1)(2, 3))
console.log(currySum(1, 2)()()(3))
实现:
function curry(cb, ...args) {
if (args.length >= cb.length) {
return cb(...args)
}
return (...rest) => {
return curry(cb, ...args, ...rest)
}
}
五、数组对象去重
var arr = [
{ id: 1, name: 'xx' },
{ id: 1, name: 'yy' },
{ id: 2, name: 'oo' },
{ id: 2, name: 'pp' },
{ id: 3, name: 'qq' }
]
var newArr = uniqBy(arr, 'id')
实现:
const uniqBy = (arr, property) => {
const map = new Map()
for (const item of arr) {
if (!map.has(item[property])) map.set(item[property], item)
}
return [...map.values()]
}