几个常见重要的手写题目

46 阅读1分钟

直接上代码

// 测试张小飞防抖
function debounce(callback, delay) {
  // 返回事件监听函数 ==> 每次事件发生都会执行
  return function (event) {
    console.log('---debounce')
    // 如果还有未执行的定时器, 清除它
    if (callback.timeoutId) {
      clearTimeout(callback.timeoutId)
    }
    // 启动延时delay的定时器, 并保证定时器id
    callback.timeoutId = setTimeout(() => {
      // 执行处理事件的函数
      callback.call(event.target, event)
      // 删除保存的定时器id
      delete callback.timeoutId
    }, delay)
  }
}
// 数组推平
function flat(arr) {
  // 此处可用reduce代替
  const arr1 = []
  arr.forEach((res) => {
    if (res.isArray() && res.some((item) => item.isArray())) {
      arr1.concat(flat(res))
    } else {
      arr1.concat(res)
    }
  })
  return arr1
}
// 数组去重
function unique2(arr) {
  return arr.reduce((acc, item) => {
    if (!acc.includes(item)) {
      acc.push(item)
    }
    return acc
  }, [])
}
//手写生拷贝
function getType(value) {
  return Object.prototype.toString.call(value).slice(8, -1)
}
function kaobei(value) {
  const taegetObj = getType(value) === 'Object' ? {} : []
  for (const key in value) {
    if (Object.hasOwnProperty.call(value, key)) {
      const element = value[key]
      if (getType(element) === 'Object' || getType(element) === 'Array') {
        taegetObj[key] = kaobei(element)
      } else {
        taegetObj[key] = element
      }
    }
  }
  return taegetObj
}
const aa = {
  a: { b: { c: 1 } }
}
const bb = kaobei(aa)
bb.a.b.c = 2
console.log(aa)

// 求数组中字符串出现的次数
const namess = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']
const newValue = namess.reduce((acc, item) => {
  // {alice:1}
  const count = acc[item] ?? 0
  return {
    ...acc,
    [item]: count + 1
  }
}, {})