面试题里的那些各类手写

最近准备初级前端面试,发现有不少手写实现什么的,例如什么手写实现bind,promise。手写ajax,手写一些算法。
翻阅了不少书籍和博客。javascript

这里作一个总结改进,算是对我后面大概为期一个月找工做的准备。html

手写实现bind()

Function.prototype._bind = function (context) {
            var self = this;
            var args = Array.prototype.slice.call(arguments, 1);
            var fBind = function () {
                var bindArgs = Array.prototype.slice.call(arguments);
                return self.apply(this instanceof fBind ? this : context, args.concat(bindArgs));
            }
            fBind.prototype = self.prototype&&Object.create(self.prototype)
            return fBind;
        }

简单的说明:前端

  • 这里之因此传参的时候须要两个数组,是由于考虑到用new以构造函数的形式调用硬绑定函数的状况:this这时是应该指向实例对象的。
  • 这样子就须要继承以前函数的方法, fBind.prototype = self.prototype&&Object.create(self.prototype)

,同时也能够用 Object.setPrototypeOf(fBind.prototype,self.prototype)
考虑到存在undefined的状况,前面加一个判断self.prototype&&.....java

  • 关于apply的第一个参数,若是考虑到以前的状况,是不能传入context的,这须要作一个判断。

像是下面的状况node

function Foo(price){ 
       
          this.price =price
            this.fn = ()=>{
                console.log('hi fn')
            }
             console.log(this.name)
        }

        Foo.prototype.sayMyName = function(){
            console.log(this.name)
        }
      var Obj1 = {
        name:'obj1'
      }
        var b =Foo._bind(Obj1)
        b() //"obj1"
        var c = new b(1000)//"i am c"
        c.name = 'i am c'
        c.sayMyName()

这里的this的指向就是c,它指向实例对象自己es6

后面以这道题为引线面试官可能会追问:面试

  • 什么是执行上下文
  • this的判断
  • call,bind的区别

手写一个函数实现斐波那契数列

首先拷一个阮神在他es6教程里的一个写法。ajax

function* fibonacci() {
  let [prev, curr] = [0, 1];
  for (;;) {
    yield curr;
    [prev, curr] = [curr, prev + curr];
  }
}

for (let n of fibonacci()) {
  if (n > 1000) break;
  console.log(n);
}

更精简的算法

const feibo= max=>{
    let [a,b,i]= [0,1,1]
    while(i++<=max) {
        [a,b] = [b,a + b ]
       console.log(b)
    }
  return a  
}

相对是很是简单的,感受也不会多问啥,就很少说了。数组

手写一个简单的ajax

let xhr = new XMLHttpRequest()

        xhr.open('get', url, true)

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
            console.log('请求完成')
                if(this.status >= 200 &&this.status<300){ 
                    conso.log('成功')
                }else{
                    consol.log('失败')
                }
            }
        }
         xhr.onerror = function(e) {
         console.log('链接失败')
        }
        xhr.send()

大概是这么个意思就差很少了,顺势可能会问一些状态码和状态值的问题,或者直接问到关于http上面的问题。

原型继承

function inherit(supertype,subtype){
            Object.setPrototypeOf(subtype.prototype,supertype.prototype)
            subtype.prototype.constructor = subtype
        }

        function Car(name,power){
            this.name=name
            this.power = power
        }

        Car.prototype.showPower = function(){
            console.log(this.power)
        }

        function Changan(price,name,power){
            this.price = price
            Car.call(this,name,power)
        }

        inherit(Car,Changan)

        Changan.prototype.showName = function(){
            console.log(this.name)
        }

        var star = new Changan(100000,'star',500)

        star.showPower()

防抖与节流

function debounce(fn,duration){
            var  timer
            window.clearTimeout(timer)
            timer = setTimeout(()=>{
                fn.call(this)
            },duration)
        }
  function throttle(fn,duration){
            let canIRun
            if(!canIRun)return
            fn.call(this)
            canIRun = false
            setTimeout(()=>{
                canIRun = true
            },duration)
        }

数组去重

我通常就用这两种,大部分状况都能应付了。

[...new Set(array)]
//hash
 function unique(array) {
      const object = {}
      array.map(number=>{
          object[number] = true
      })
      return Object.keys(object).map(//.......)
  }//大概是这样的意思,写法根据数组的不一样可能会有所改变

深拷贝

应该是面试里面手写xxx出现频率最高的题了,不管是笔试仍是面试。
老是让你手写实现深拷贝函数。

事实上,js并不能作到真正彻底的标准的深拷贝

因此无论你写什么样的深拷贝函数都会有不适用的地方,这取决于使用的场景和拷贝的对象,若是面试官在这上面钻研比较深的话,是很难作到完美的。

既然这样就写个将就一点的深拷贝吧,面向面试的那种。

function deepClone(item) {
      return result;
  }
  • 首先在类型判断上作一个选择,通常状况来讲,用new建立的实例对象用typeof判断会出问题的,相比之下instanceof也不靠谱。这里面相对比较靠谱的Object.prototype.toString.call(item)。(这个其实也不兼容到所有状况和性能要求,可是面向面试代码可读性会高一点)。

    type = Object.prototype.toString.call(item).slice(8,this.length-1),
    //[object String],[object Array],[object Object]
  • 函数的拷贝,这里不能使用bind,会改变this指向或影响后续使用call调用该拷贝的函数,大部分状况是没必要要的,这里就直接赋值吧。
  • 因而这里能够把基本数据类型和Function放一块儿。

    fk= ['String','Number','Boolean','Function'].indexOf(type)>-1
  • dom对象的拷贝: result = item.cloneNode(true);
  • 忽略正则
  • Date[object Object], [object Array]放到后面的判断

    let other = {           //须要递归或者其余的操做
                          Array() {
                              result = []
                              item.forEach((child, index)=>{
                                  hash.set(item, result);
                                  result[index] = deepClone(child,hash)
                              })
                          },
                          Date(){
                              result = new Date(item)
                          },
                          Object(){
                              result = {}
                              Reflect.ownKeys(item).forEach(child=>{
                                  hash.set(item, result);
                                  result[child] = deepClone(item[child],hash)
                              })
                          }
                      }
                      other[type]()

这样子是否是相对清晰一些了,应付通常的状况应该差很少了,可是没考虑循环引用

这里给个思路是使用ES6WeakMap,不知道的兄弟能够看看阮神的ES6博客,为防止爆栈,我把循环引用直接扔给它,完美拷贝。
就至关于

var wm = new WeakMap()

var obj = {
   name:null
 }
obj.name = obj
wm.set(obj,wm.get(obj))
console.log(wm)

如今就须要在开头检查一下循环引用,而后直接返回WeakMap对象键名为item参数对象的值
因此最终代码就是

function deepClone(item,hash = new WeakMap()) {
       if (!item) return item
       if (hash.has(item))return hash.get(item);  //检查循环引用
           var result,
             type = Object.prototype.toString.call(item).slice(8,this.length-1),
             fk= ['String','Number','Boolean','Function'].indexOf(type)>-1

               if(fk){
                   result = item;//直接赋值
               }else if(item.nodeType && typeof item.cloneNode === "function"){
                   result = item.cloneNode(true);          //是不是dom对象
               }else{

                   let other = {           //须要递归或者其余的操做
                       Array() {
                           result = []
                           item.forEach((child, index)=>{
                               hash.set(item, result);
                               result[index] = deepClone(child,hash)
                           })
                       },
                       Date(){
                           result = new Date(item)
                       },
                       Object(){
                           result = {}
                           Reflect.ownKeys(item).forEach(child=>{
                               hash.set(item, result);
                               result[child] = deepClone(item[child],hash)
                           })
                       }
                   }
                   other[type]()
               }
       return result;
   }

意思就大概是这个意思,固然深拷贝的方法有不少,甚至不必定用到递归。面试官总会有找茬的地方的。
我以为我写的这个仍是知足我如今找工做的级别要求的。

而后是我用来测试的对象

var obj1 = {
   name:'obj1',
   one : {
       a:new Date(),
       b:new String('1-2'),
       c:new Array(['this','is',1,{a:23}]),
       d: function () {
           if(true){
               return 'd'
           }
       },
       e:new Number(15),
       f:new Boolean(true)
   },
   two(x){
       console.log(x+' '+this.name)
   },
   three : [
       {
           a:'this is a',
            b:document.body,  
           c:{
               a:[1,2,3,4,5,[13,[3],true],10],
               b:{
                   a:{
                       a:[1,2,3]
                   },
                   b:2
               }
           }
       },
   ],
   four:[1,2]
}
    obj1.name=obj1
    obj1.four[3] = obj1
   var copy = deepClone(obj1)

   console.log(copy)
   copy.two.call(window,'hi')

## new

简单说下大概是这么一个过程

  • 建立一个空对象
  • 执行传入的构造函数,执行过程当中对 this 操做就是对 这个空对象 进行操做。
  • 返回这个空对象

模拟须要考虑的问题

  • 是一个空对象,这里面的写法obj原型链是没有上一级的,即不存在与其余任何对象之间的联系,虽然在这里面没多少区别:var obj = Object.create(null),
  • this指向这个空对象:let rt = Constructor.apply(obj, arguments);
  • 能够访问构造函数的原型链, Object.setPrototypeOf(obj, Constructor.prototype);
  • 若是构造函数有返回值,而且是一个对象,那么实例对象拿到的就是这个对象(应该只是值,并非引用)。因此这里要作个判断return typeof rt === 'object' ? rt : obj;

    最终的代码

function _new(){
    var obj =  Object.create(null),
    Constructor = [].shift.call(arguments);
    Object.setPrototypeOf(obj, Constructor.prototype);
    let  rt = Constructor.apply(obj, arguments);
    return rt instanceof Object ? rt : obj;
}

<br/>
<br/>

快速排序

快排
:代码精简了一点

function quickSort(arr){
       if(arr.length<=1)return arr
       var index = Math.floor(arr.length/2),
           number = arr.splice(index,1)[0],
           left = [],
           right = [];
       arr.forEach(item=>{
        item<=number?left.push(item):right.push(item)
       })
       return quickSort(left).concat([number],quickSort(right))
   }

这期间会不断更新并修改,这里面的手写实现您若是有更好的写法或者新的思路,也但愿能够说明交流。最后谢谢大佬些的观看。

相关文章
相关标签/搜索