• 回答数

    0

  • 浏览数

    598

  • 收藏数

    0

作者:团子良 发表于 2022-12-7 17:17:13
跳转到指定楼层
前言
不知道今年大家有没有感受到来自互联网的“寒气”,至少我是感受到了,面试的时候手写代码时很常见很常见的事情了。有时候没遇到过还真一时半会写不出来,企业招聘的要求也是越来越高,尤其是一些大厂会对 JS 的功底有着更加苛刻的要求,所以学会手写常见的 JS 模块好像已经快变为一个基本技能了,也慢慢变为我们手写 webpack 手写 mini-vue 的一个 coding 基础 了。当然我们也不完全是为了去准备面试而去学习这些常见模块。死磕这些难啃的骨头之后,你会从中学到很多优秀的思想,对你的职业生涯也是很有帮助的。而且阅读代码本身就是一个很好的习惯,读懂并且理解写代码人的思维逻辑更加重要。
本文中涉及到的手写模块,大多数都是从网上的博客、面筋、牛客网以及自己的面试经验借鉴而来的。希望能对你有个帮助。
基础手写全排列(力扣原题)
要求以数组的形式返回字符串参数的所有排列组合。
注意:
  • 字符串参数中的字符无重复且仅包含小写字母
  • 返回的排列组合数组不区分顺序
  1. const _permute = string => {
  2.   const result = []
  3.   const map = new Map()
  4.   const dfs = (path) => {
  5.     if (path.length === string.length) {
  6.       result.push(path)
  7.       return
  8.     }
  9.     for (let i = 0; i < string.length; i++) {
  10.       if (map.get(string[i])) continue
  11.       map.set(string[i], true)
  12.       path += string[i]
  13.       dfs(path)
  14.       path = path.substring(0, path.length - 1)
  15.       map.set(string[i], false)
  16.     }
  17.   }
  18.   dfs('')
  19.   return result
  20. }
  21. console.log(_permute('abc')) // [ 'abc', 'acb', 'bac', 'bca', 'cab', 'cba' ]
复制代码
instanceof
  • 如果 target 为基本数据类型直接返回 false
  • 判断 Fn.prototype 是否在 target 的隐式原型链上


  1. const _instanceof = (target, Fn) => {
  2.   if ((typeof target !== 'object' && typeof target !== 'function') || target === null)
  3.   return false
  4.   
  5.   let proto = target.__proto__
  6.   while (true) {
  7.     if (proto === null) return false
  8.     if (proto === Fn.prototype) return true
  9.     proto = proto.__proto__
  10.   }
  11. }
  12. function A() {}
  13. const a = new A()
  14. console.log(_instanceof(a, A)) // true
  15. console.log(_instanceof(1, A)) // false
复制代码


Array.prototype.map
  • map 中的 exc 接受三个参数,分别是: 元素值、元素下标和原数组
  • map 返回的是一个新的数组,地址不一样
  1. // 这里不能直接使用箭头函数,否则无法访问到 this
  2. Array.prototype._map = function (exc) {
  3.   const result = []
  4.   this.forEach((item, index, arr) => {
  5.     result[index] = exc(item, index, arr)
  6.   })
  7.   return result
  8. }
  9. const a = new Array(2).fill(2)
  10. console.log(a.map((item, index, arr) => item * index + 1)) // [1,3]
  11. console.log(a._map((item, index, arr) => item * index + 1))// [1,3]
复制代码


Array.prototype.filter
  • filter 中的 exc 接受三个参数,与map一致,主要实现的是数组的过滤功能,会根据 exc 函数的返回值来判断是否“留下”该值。
  • filter 返回的是一个新的数组,地址不一致。



  1. Array.prototype._filter = function (exc) {
  2.   const result = []
  3.   this.forEach((item, index, arr) => {
  4.     if (exc(item, index, arr)) {
  5.       result.push(item)
  6.     }
  7.   })
  8.   return result
  9. }
  10. const b = [1, 3, 4, 5, 6, 2, 5, 1, 8, 20]

  11. console.log(b._filter(item => item % 2 === 0)) // [ 4, 6, 2, 8, 20 ]
复制代码


Array.prototype.reduce
  • reduce 接受两个参数,第一个为 exc 函数,第二个为初始值,如果不传默认为 0
  • reduce 最终会返回一个值,当然不一定是 Number 类型的,取决于你是怎么计算的,每次的计算结果都会作为下次 exc 中的第一个参数
  1. Array.prototype._reduce = function (exc, initial = 0) {
  2.   let result = initial
  3.   this.forEach((item) => {
  4.     result = exc(result, item)
  5.   })
  6.   return result
  7. }
  8. console.log(b.reduce((pre, cur) => pre + cur, 0)) // 55
  9. console.log(b._reduce((pre, cur) => pre + cur, 0)) // 55
复制代码
Object.create
Object.create() 方法用于创建一个新对象,使用现有的对象来作为新创建对象的原型(prototype)。
  1. Object.prototype._create = function (proto) {
  2.   const Fn = function () { }
  3.   Fn.prototype = proto
  4.   return new Fn()
  5. }
  6. function A() { }
  7. const obj = Object.create(A)
  8. const obj2 = Object._create(A)
  9. console.log(obj.__proto__ === A) // true
  10. console.log(obj.__proto__ === A) // true
复制代码
Function.prototype.call
call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
  1. Function.prototype._call = function (ctx, ...args) {
  2.   // 如果不为空,则需要进行对象包装
  3.   const o = ctx == undefined ? window : Object(ctx)
  4.   // 给 ctx 添加独一无二的属性
  5.   const key = Symbol()
  6.   o[key] = this
  7.   // 执行函数,得到返回结果
  8.   const result = o[key](...args)
  9.   // 删除该属性
  10.   delete o[key]
  11.   return result
  12. }

  13. const obj = {
  14.   name: '11',
  15.   fun() {
  16.     console.log(this.name)
  17.   }
  18. }

  19. const obj2 = { name: '22' }
  20. obj.fun() // 11
  21. obj.fun.call(obj2) // 22
  22. obj.fun._call(obj2) // 22
复制代码
Function.prototype.bind
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
  1. const obj = {
  2.   name: '11',
  3.   fun() {
  4.     console.log(this.name)
  5.   }
  6. }
  7. Function.prototype._bind = function (ctx, ...args) {
  8.   // 获取函数体
  9.   const _self = this
  10.   // 用一个新函数包裹,避免立即执行
  11.   const bindFn = (...reset) => {
  12.     return _self.call(ctx, ...args, ...reset)
  13.   }
  14.   return bindFn
  15. }
  16. const obj2 = { name: '22' }
  17. obj.fun() // 11
  18. const fn = obj.fun.bind(obj2)
  19. const fn2 = obj.fun._bind(obj2)
  20. fn() // 22
  21. fn2() // 22
复制代码
New 关键字
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
  1. const _new = function(constructor) {
  2.   // 创建一个空对象
  3.   const obj = {}
  4.   // 原型链挂载
  5.   obj.__proto__ = constructor.prototype;
  6.   // 将obj 复制给构造体中的 this,并且返回结果
  7.   const result = constructor.call(obj)
  8.   // 如果返回对象不为一个对象则直接返回刚才创建的对象
  9.   return typeof result === 'object' && result !== null ? : result : obj
  10. }
复制代码
浅拷贝
  1. const _shallowClone = target => {
  2.   // 基本数据类型直接返回
  3.   if (typeof target === 'object' && target !== null) {
  4.     // 获取target 的构造体
  5.     const constructor = target.constructor
  6.     // 如果构造体为以下几种类型直接返回
  7.     if (/^(Function|RegExp|Date|Map|Set)$/i.test(constructor.name)) return target
  8.     // 判断是否是一个数组
  9.     const cloneTarget = Array.isArray(target) ? [] : {}
  10.     for (prop in target) {
  11.       // 只拷贝其自身的属性
  12.       if (target.hasOwnProperty(prop)) {
  13.         cloneTarget[prop] = target[prop]
  14.       }
  15.     }
  16.     return cloneTarget
  17.   } else {
  18.     return target
  19.   }
  20. }
复制代码
深拷贝
实现思路和浅拷贝一致,只不过需要注意几点
  • 函数 正则 日期 ES6新对象 等不是直接返回其地址,而是重新创建
  • 需要避免出现循环引用的情况
  1. const _completeDeepClone = (target, map = new WeakMap()) => {
  2.   // 基本数据类型,直接返回
  3.   if (typeof target !== 'object' || target === null) return target
  4.   // 函数 正则 日期 ES6新对象,执行构造题,返回新的对象
  5.   const constructor = target.constructor
  6.   if (/^(Function|RegExp|Date|Map|Set)$/i.test(constructor.name)) return new constructor(target)
  7.   // map标记每一个出现过的属性,避免循环引用
  8.   if (map.get(target)) return map.get(target)
  9.   map.set(target, true)
  10.   const cloneTarget = Array.isArray(target) ? [] : {}
  11.   for (prop in target) {
  12.     if (target.hasOwnProperty(prop)) {
  13.       cloneTarget[prop] = _completeDeepClone(target[prop], map)
  14.     }
  15.   }
  16.   return cloneTarget
  17. }
复制代码




分享:
回复

使用道具

成为第一个回答人

高级模式 评论
您需要登录后才可以回帖 登录 | 立即注册 微信登录