Interview handwritten code list

Time:2021-3-9
Anti chattering function

const debounce = (fn, wait) => {
     let _ = ''
     return (...arg) => {
         clearTimeout(_)
             _ = setTimeout(() => {
             fn.apply(this, arg)
         }, wait)
     }
}
input.addEventListener("input", debounce(ajax, 1000));
Throttling function

const throttle = (fn, s) => {
 let a = +new Date(),
    _ 
 return (...arg) => {
    let b = +new Date() - a
        if (b > s) {
        _ = setTimeout(() => {
       fn(arg);
        _ = ''
     }, s)
        a = +new Date()
    }
 }
}

input.addEventListener("input", throttle(ajax, 1000));
Deep copy (solve circular reference)


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 (const key in target) {
            cloneTarget[key] = clone(target[key], map);
        }
        return cloneTarget;
    } else {
        return target;
    }
}
Function Kriging

let curry = fn => ju = (...arg) => arg.length == fn.length ? fn(...arg) : (...args) => ju(...arg, ...args)
JS for floating point operation

let float_ = (...arg) => {    
    let len = Math.max(...arg.map(i => {
        let [, _] = String(i).split('.')
        console.log(_)
        return _ ? _.length : ''
    }))
    return arg.reduce((all, i) => all + i * len / len, 0)
}
Handwritten Ajax

let ajax=obj=>{
    let _=Object.assign({
        methods:'GET',
        url:'www.xxx.com',
        data:''
    },obj)
    return new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest,
            sendData = ''
        if(_.data){
            for(let i in _.data){
                sendData += `&${i}=${_.data[i]}`
            }
        }
        let url = sendData ? `${obj.url}?${sendData}` : obj.url
        if (methods = 'GET') {
            xhr.open('GET', obj.url, true)
            xhr.send(sendData)
        }
        if (methods = 'POST') {
            xhr.open('POST', obj.url, true)
            xhr.send(sendData.slice(1))
        }
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200 || XHR.status === 304) {
                    resolve(JSON.parse(xhr.responseText))
                } else {
                    reject(Error)
                }
            }
        }
    })
}
Queue function (call function asynchronously or not)

let stack=[],
    index=0
function next(){
    var fn=stack[i]
    index += 1 
    if (typeof fn == 'function') {
        fn();
    }
}    
function fn1(){
    console.log ('first call ')
    next();
}
function fn2(){
    setTimeout(function() {
        console.log ('the second is called ');
        next();
    }, 1000)
}
function fn3() {
    console.log ('third call ');
    next();
}
stack.push(fn1, fn2, fn3)
next();
Using async to write asynchronous functions (whether the picture is loaded correctly)

async function load(url) {
    var image = new Image();
    image.onload  =Function () {// the image is loaded successfully. Call the resolve method
        return console.log(image)
    };
    image.onerror  =Function () {// image loading failed, call reject method
        Throw 'wrong'
    };
    image.src = url;
}
function
~async function img() {
    return await load(
        'https://www.xxx.com'
    )
}()
Instanceof function

function Instanceof_(obj, fn) {
    while (true) {
        if (obj.__proto__ === null) return false
        if (obj.__proto__ === fn.prototype) return true
         obj= obj.__proto__;
    }
}
Call function

Function.prototype.call_ = function() {
    let obj = Array.from(arguments)[0] || window,
        arg = Array.from(arguments).slice(1),
        key = Symbol(),
        result
    obj[key] = this
    result = obj[key](...arg)
    delete obj[key]
    return result
}
Bind function

Function.prototype.bind_ = function() {
    let obj = Array.from(arguments)[0] || window,
        arg = Array.from(arguments).slice(1),
        self = this
    return function(){
        let args=Array.from(arguments).slice(1)
        return self.call(obj,[...arg,...args])
    }
}
EventEmitter (collect and publish)

class EventEmitter {
    constructor() {
        this.obj = {}
    }
    on(key, fn) {
        let Events = []
        Event.push(fn)
        this.obj[key] = Event
    }
    emit(key, ...arg) {
        let Events = this.obj[key]
        if (Events.length) {
            Events.forEach(i => i(...arg))
        }
    }
}
Sleep function

function sleep(s){
     return new Promise(resolve=>{
     setTimeout(resolve,s)
  })
}

sleep(1000).then(()=>alert(1))

 or

!async function run() {
 await sleep(1500);
 console.log('start await');
}()
Traversal of DOM nodes

function one_(node) {
    if (node.nodeType == 1) {
        return node.tagName.toLowerCase()
    }
    for (var i = 0; i < node.childNodes.length; i++) {
        if (node.childNodes[i].nodeType === 1) {
            one_(node.childNodes[i])
        }
    }
}
LRU algorithm

class Lru_cache {
    constructor(max) {
        this.max = max;
        this.cache = new Map();
    }
    get(key) {
        let value = this.cache.get(key);
        if (!value) return;
        this.cache.delete(key);
        this.cache.set(key, value);
        return value;
    }
    add(key, value) {
        if (this.cache.size > this.max - 1) {
            const keys = this.cache.keys().next().value;
            this.cache.delete(keys);
        }
        this.cache.set(key, value);
    }
}
Es5 inheritance

function Far(name){
        this.name = name;
        this.color = ["red","green","blue"];
    }
    Far.prototype.sayName = function(){
        console.log(this.name);
    };
function Son(name,age){
        Far.call(this,name);
        this.age  = age;
    }
    Son.prototype=Object.creat(Far.prototype)
    San.prototype.constructor = San
ES6 inheritance

class Big {
    constructor(name) {
        this.name = name
    }
    getName() {
        return this.name
    }
}
class Small extends Big {
    constructor(name, sex) {
        super(name)
        this.sex = sex
    } 
    getSex() {
        return this.sex
    }
}

var big = new Big('o( ̄ヘ ̄o#)')
var small = new Small('o( ̄ヘ ̄o#)', '♀')
console.log(big.getName())
console.log(small.getName())
Handwriting Object.create

function _create(obj) {
    function C() {}
    C.prototype = obj;
    return new C();
}
Handwritten NEW

function new_(fn,arg){
    let obj={}
    Object.getPrototypeOf(obj,fn.prototype)
    fn.apply(obj,arg)
    return obj
}
Handwritten reduce

Array.prototype.reduce_2 = function(fn, back) {
    let arr = this
    for (var i=0; i < arr.length; i++) {
        return !back ? fn(arr[i], arr[i + 1], i + 1, arr) : fn(back, arr[i], i, arr)
    }
}
Handwritten map

Array.prototype.map_ = function(fn) {
    let arr = this
    let arr_ = []
    for (let i = 0; i < arr.length; i++) {
        arr_[i] = fn(arr[i], i, arr)
    }
    return arr_
}
Handwritten filter

Array.prototype.filter_=function(fn){
    let arr=this,
    arr_=[]
    for (let i = 0; i < arr.length; i++) {
        if(fn(arr[i],i,arr)){
            arr_[i]=arr[i]
        }
    }
    return arr_
}
Implement Bubble Sort

function bubbing_(arr) {
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
            }
        }
    }
    return arr
}
Implementation of selective sorting

function select_(arr) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[i]) {
                [arr[j], arr[i]] = [arr[i], arr[j]]
            }
        }
    }
    return arr
}
Implement insert sort

function insert(array) {
    for (let i = 1; i < array.length; i++) { 
        var j = i - 1; 
        while (j >= 0 && array[j] > array[i]) { 
            [arr[j], arr[i]] = [arr[i], arr[j]] 
            j--;
        }
    }
    return array;
}
Implement quick sort

function bubbing_(arr) {
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
            }
        }
    }
    return arr
}
Implement Bubble Sort

function fast_(arr) {
    let len = arr.length,
        r = [],
        l = [],
        bsc = arr[0]
    if (len < 2) {
        return arr
    }
    for (let i = 1; i < len; i++) {
        if (arr[i] < bsc) {
            l.push(arr[i])
        } else {
            r.push(arr[i])
        }
    }
    return [...k(l), bsc, ...k(r)]
}
Realize dichotomy

function getIndex(arr, num) {
    arr.sort(a,b=>a-b)
    var start = 0,
        end = arr.length - 1
    while (start <= end) {
        var mid = Math.floor((start + end) / 2)
        if (num == arr[mid]) {
            return mid
        }
        if (num > arr[mid]) {
            start = mid + 1
        }
        if (num < arr[mid]) {
            end = mid - 1
        }
    }
    return false  
}
Implement promise

class MyPromise {
  constructor(fn) {
    this.status = "padding";
    this.data = "";
    this.error = "";
    this.resolveArr = [];
    this.rejectArr = [];
    let resolve = data => {
      setTimeout(() => {
        if (this.status == "padding") {
          this.data = data;
          this.status = "resolved";
          this.resolveArr.forEach(i => i());
        }
      }, 0);
    };
    let reject = error => {
      setTimeout(() => {
        if (this.status == "padding") {
          this.error = error;
          this.status = "rejected";
          this.rejectArr.forEach(i => i());
        }
      }, 0);
    };
    fn(resolve, reject);
  }
  then(Onresolve, Onreject) {
    if (this.status == "resolved") {
      return new MyPromise((resolve, reject) => {
        let res = Onresolve(this.data);
        if (res instanceof MyPromise) {
          res.then(resolve, reject);
        } else {
          resolve(res);
        }
      });
    }
    if (this.status == "rejected") {
      return new MyPromise((resolve, reject) => {
        let res = Onreject(this.error);
        if (res instanceof MyPromise) {
          res.then(resolve, reject);
        } else {
          resolve(res);
        }
      });
    }
    if (this.status == "padding") {
      return new MyPromise((resolve, reject) => {
        this.resolveArr.push(() => {
          let res = Onresolve(this.data);
          if (res instanceof MyPromise) {
            res.then(resolve, reject);
          } else {
            resolve(res);
          }
        });
        this.rejectArr.push(() => {
          let res = Onreject(this.error);
          if (res instanceof MyPromise) {
            res.then(resolve, reject);
          } else {
            resolve(res);
          }
        });
      });
    }
  }
  static resolve(data) {
    return new MyPromise(resolve => resolve(data));
  }
  static reject(error) {
    return new MyPromise(reject => reject(error));
  }
}