手写系列

133 阅读1分钟

冒泡排序:

let array = [8, 6, 1, 7, 5, 4, 2, 3]
function bubbling (arr) {
  let length = arr.length
  for (let i = 0; i < length; i++) {
    for (let j = 0; j < length - i - 1; j ++) {
      if (arr[j] > arr[j+1]) {
        let temp = arr[j]
        arr[j] = arr[j+1]
        arr[j+1] = temp
      }
    }
  }
  return arr
}

防抖:

function debounce(fn, delay) {
  let timer = null
  return function() {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this)
    }, delay)
  }
} 

节流:

function throttle(fn, delay) {
  let isRun = true
  return function () {
    if (!isRun) return
    isRun = false
    setTimeout(() => {
      fn.call(this, arguments)
      isRun = true
    }, delay)
  }
}

Promise:

function promiseAsync() {
  let fulfilledCallback, rejectedCallback
  setTimeout(() => {
    let random = Math.random()
    if (random > 0.5) {
      fulfilledCallback(random)
    } else {
      rejectedCallback(random)
    }
  })
  return {
    then: function(_fulfilled, _rejected) {
      fulfilledCallback = _fulfilled
      rejectedCallback = _rejected
    }
  }
}
promiseAsync().then(fulCallBack, rejectCallBack)

模拟call:

Function.prototype.call2 = function(context) {
  let context = context
  context.fn = this
  let args = []
  for (let item of arguments) {
    args.push(item)
  }
  let result = eval('context.fn('+ args +')')
  delete context.fn
  return result
}
let obj = {
  value: 1
}
function bar() {
  console.log(this.value)
}
bar.call2(obj)

模拟实现apply:

Function.prototype.apply2 = function(context, arr) {
  var context = Object(context) || Window
  context.fn = this
  var result
  if (!arr) {
    result = context.fn()
  } else {
    var list = []
    for (let item of arr) {
      list.push(item)
    }
    result = eval('context.fn('+ list +')')
  }
  delete context.fn
  return result
}

模拟实现bind:

Function.prototype.bind2 = function(context) {
  var self = this
  var args = Array.prototype.slice.call(arguments, 1)
  Fn = function () {}
  Bn = function () {
     var bindArgs= Array.prototype.slice.call(arguments)
     return self.apply(this instanceOf Fn ? this : context, args.concat(bindArgs))
  }
  Fn.prototype = this.prototype
  Bn.prototype = new Fn()
  return Bn
}

模拟实现new:

function Factory () {
  var obj = new Object()
  Constructor = [].prototype.shift(arguments)
  obj._proto_ = Constroutor.prototype
  var ret = Constructor.apply(obj, arguments)
  return typeof ret === 'object' ? ret : obj
}