面试手写代码练习

339 阅读1分钟

借鉴了这两位大佬,用于面试的手写代码

juejin.cn/post/684490… juejin.cn/post/706158…

1. new操作符

function New(fn) {
  let res = {};
  if (fn.prototype !== null) {
    res._proto_ = fn.prototype;
  }
  let arg = [...arguments].slice(1);
  let ret = fn.apply(res, arg);
  if (
    (typeof ret === "object" || typeof ret === "function") &&
    ret !== null
  ) {
    return ret;
  }
  return res;
}

2.深拷贝

function clone(target, map = new WeakMap()) {
  if (typeof target === "object") {
    let cloneTarget = Array.isArray(target) ? [] : {};
    if (map.get(target)) {
      return map.get(target);
    }
    map.set(target, cloneTarget);
    for (let key in target) {
      cloneTarget[key] = clone(target[key], map);
    }
    return cloneTarget;
  } else {
    return target;
  }
}

3.call

Function.prototype.Call = function (context = window) {
  if (typeof this !== "function") {
    throw new Error("Type error");
  }
  context.fn = this;
  let args = [...arguments].slice(1);
  let result = context.fn(...args);
  delete context.fn;
  return result;
};

4.apply

Function.prototype.Apply = function (context = window) {
  if (typeof this !== "function") {
    throw new Error("Type Error");
  }
  context.fn = this;
  let result;
  if (arguments[1]) {
    result = context.fn(...arguments[1]);
  } else {
    result = context.fn();
  }
  delete context.fn;
  return result;
};

5.bind

Function.prototype.Bind = function (context = window) {
  if (typeof this !== "function") {
    throw new Error("Type Error");
  }
  let fn = this;
  let args = [...arguments].slice(1);
  return function Fn() {
    let bindArg = args.concat(...arguments);
    return fn.apply(this instanceof Fn ? this : context, bindArg);
  };
};

6.平铺转树型

function lineToTree(data) {
  let map = {};
  let treeList = [];
  for (let city of data) {
    if (city.pid === 0) {
      treeList.push(city);
      map[city.id] = city.children = [];
    } else {
      if (map[city.pid]) {
        map[city.pid].push(city);
        map[city.id] = city.children = [];
      }
    }
  }
  return treeList;
}

7.树型转平铺

function treeToLine(data) {
      let res = [];
      data.map((el) => {
        res.push(el);
        el.children?.length && res.push(...treeToLine(el.children));
        el.children = [];
      });
      return res;
    }
  }

用于测试的树形结构:

var data = [
    {
      id: "a",
      pid: 0,
      value: "陕西",
      children: [
        {
          id: 1,
          pid: "a",
          value: "西安",
          children: [
            {
              id: 21,
              pid: "01",
              value: "长沙",
              children: [
                { id: 25, pid: "21", value: "渭南" },
                { id: 26, pid: "21", value: "咸阳" },
              ],
            },
            { id: 22, pid: "1", value: "常德" },
            { id: 23, pid: "1", value: "岳阳" },
          ],
        },
        { id: 2, pid: "a", value: "渭南" },
        { id: 3, pid: "a", value: "咸阳" },
      ],
    },
    {
      id: "b",
      pid: 0,
      value: "广东",
      children: [
        { id: 11, pid: "b", value: "广州" },
        { id: 12, pid: "b", value: "深圳" },
        { id: 13, pid: "b", value: "潮汕" },
      ],
    },
    {
      id: "c",
      pid: 0,
      value: "湖南",
      children: [],
    },
  ];

8.防抖

function debounce(fn, wait) {
    let timer = null;
    return function () {
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, wait);
    };
  }

9.节流

function throttle(fn, wait) {
    let valid = true;
    return function () {
      if (valid) {
        setTimeout(() => {
          fn.apply(this, arguments);
          valid = true;
        }, wait);
        valid = false;
      } else {
        return false;
      }
    };
}

10.去重

function unique(arr) {
    return [...new Set(arr)];
}
function unique(arr) {
    return arr.filter((item, index, array) => {
        return array.indexOf(item) === index;
    });
}

这是现在掌握的,后续再添加。。。。