面试记录专刊:第8天

235 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第7天,点击查看活动详情

今日复习计划:手写前端API。

一.前端知识

1. 数据扁平化

const arr = [1, [2, [3], [{ a: 1 }]]];
console.log(arr.flat(2)) //  [ 1, 2, 3, { a: 1 } ]
const arr = [1, [2, [3], [{ a: 1 }]]];
function myFlat(array) {
  let res = [];
  array.forEach((item) => {
    if (Array.isArray(item)) {
      res = [...res, ...myFlat(item)];
    } else {
      res.push(item);
    }
  });
  return res;
}
console.log(myFlat(arr)); // [ 1, 2, 3, { a: 1 } ]

2. 数据去重

使用set

const arr = [1, 2, 3, 2, 4, 1];
console.log([...new Set(arr)]);
const arr = [1, 2, 3, 2, 4, 1];
let res = arr.filter((item, index, array) => {
  return array.indexOf(item) === index;
});

console.log(res);

3. 防抖

function debouce(fun, time) {
  let timer;

  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fun.apply(this.arguments);
      timer = 0;
    }, time);
  };
}

4. 节流

function throttle(fun, time) {
  let timer;

  return function () {
    if (timer) {
      return;
    }
    fun.apply(this, ...arguments);
    timer = setTimeout(() => {
      clearTimeout(timer);
      timer = 0;
    }, time);
  };
}

5. curry

function curry(fn) {
  function judge(...args) {
    return args.length === fn.length
      ? fn(...args)
      : (...arg) => judge(...args, ...arg);
  }

  return judge;
}

6. instanceof

function myInstanceof(left, right) {
  let proto = left.__proto__;
  while (true) {
    if (proto == null) {
      return false;
    }
    if (proto === right.prototype) {
      return true;
    }
    proto = proto.__proto__;
  }
}

7. Object.create

function myObjectCreate(proto) {
  if (typeof proto !== "object" && typeof proto !== "function") {
    return new Error("xxxxx");
  }
  function Fn() {}
  Fn.prototype = proto;
  let obj = new Fn();
  if (proto === null) {
    // 创建一个没有原型对象的对象,Object.create(null)
    obj.__proto__ = null;
  }
  return obj;
}

8. Object.assign

Object.assign2 = function(target, ...source) {
    if (target == null) {
        throw new TypeError('Cannot convert undefined or null to object')\
    }
    let ret = Object(target) 
    source.forEach(function(obj) {
        if (obj != null) {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    ret[key] = obj[key]
                }
            }
        }
    })
    return ret
}

二.算法

三.面经

四.其他

今天进入了瓶颈期,开始抵抗复习。希望尽早上岸吧。

He said, one day you’ll leave this world behind,
so live a life you will remenber