Handwritten code of front-end written test

1. Flat nested array / flat implementation

Description: expand and tile a nested array into an array with only one layer.

let array = [1, [1, 2, 3], [1, [2, {}]] ]
handle(array) // [1, 1, 2, 3, 1, 2, {}]

Method 1:

const handle = array => JSON.parse(`[${JSON.stringify(arr).replace(/\[|]/g,'')}]`)
handle(array)   // [ 1, 1, 2, 3, 1, 2, {} ]

Knowledge points: JSON.parse()/JSON.stringify(),String.prototype.replace()

Method two:

const handle = array => array.reduce((accumulator, currentValue) => accumulator.concat(Array.isArray(currentValue) ? hanlde(currentValue), currentValue), [])
handle(array)   // [ 1, 1, 2, 3, 1, 2, {} ]

Knowledge points: Array.prototype.reduce(),Array.prototype.concat()

Method three:

const handle = array => {
    while(array.some(item => Array.isArray(item))) {
        array = [].concat(...array)
    }
    return array
}
handle(array)   // [ 1, 1, 2, 3, 1, 2, {} ]

Knowledge points: while,Array.prototype.some(),Spread syntax

Other methods:

2. Array de duplication

Description: filters out duplicate elements in an array.

let array = [1, 2, 1, '3', '3', 0 , 1]
handle(array)   // [1, 2, '3', 0]

Method 1:

const handle = array => [...new Set(array)]
handle(array)   // [ 1, 2, '3', 0 ]

Knowledge points: Set

Method two:

const handle = array => array.reduce((accumulator, currentValue) => {
    !accumulator.includes(currentValue) && accumulator.push(currentValue)
    return accumulator
}, [])
handle(array)   // [ 1, 2, '3', 0 ]

Knowledge points: Array.prototype.includes()

Method three:

const handle = array => {
    let map = new Map()
    return array.filter(item => map.has(item) ? false : map.set(item))
}
handle(array)   // [ 1, 2, '3', 0 ]

Knowledge points: Map,Array.prototype.filter()

Other methods:

3. Analog bind implementation

Function.prototype.bind = function () {
    let self = this, args = Array.from(arguments), context = args.shift();
    return function () {
        return self.apply(context, args.concat(...arguments))
    };
};

Knowledge points: apply,call,bind

4. Simulate New implementation

const handle = function() {
    let fn = Array.prototype.shift.call(arguments)
    let obj = Object.create(fn.prototype)
    let o = fn.apply(obj, arguments)
    return typeof o === 'object' ? o : obj;
}

Knowledge points: Object.create()

5. Format numbers

const num = 123456789;
const handle = num => String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
handle(num) // 123,456,789

Knowledge points: regular expression ,String.prototype.replace()

6. Palindrome judgment

const num = 123456654321;
const str = 'abababababab';
const handle = params => {
    let str_1 = String(params).replace(/[^0-9A-Za-z]/g, '').toLowerCase();
    let str_2 = str_1.split('').reverse().join();
    return str_1 === str_2 ? true : false
}
handle(num) // true
handle(str) // false

Knowledge points: String.prototype.split(),Array.prototype.join()

7. Function throttling

timer

const handle = (fn, interval) => {
    let timeId = null;
    return function() {
        if (!timeId) {
            timeId = setTimeout(() => {
                fn.apply(this, arguments)
                timeId = null
            }, interval)
        }
    }
}

Knowledge points: window.setTimeout

time stamp

const handle = (fn, interval) => {
    let lastTime = 0
    return function () {
        let now = Date.now();
        if (now - lastTime > interval) {
            fn.apply(this, arguments)
            lastTime = now
        }
    }
}

8. Function anti shake

const handle = (fn, delay) => {
    let timeId;
    return function() {
        if (timeId) clearTimeout(timeId)
        timeId = setTimeout(() => {
            fn.apply(this, arguments)
        }, delay)
    }
}

Difference between function throttling and function anti shake: function throttling and function anti shake are easy to be confused. It can be said that for function throttling, someone knocks frequently outside the door, but the guard decides whether to open the door according to a fixed time. For function anti shake, someone knocks frequently outside the door, and the guard decides whether to open the door according to the last knock.

Knowledge points: window.clearTimeout

9. Publish and subscribe mode

class Pubsub {
    constructor() {
        this.handles = {}
    }
    subscribe(type, handle) {
        if (!this.handles[type]) {
            this.handles[type] = []
        }
        this.handles[type].push(handle)
    }
    unsubscribe(type, handle) {
        let pos = this.handles[type].indexOf(handle)
        if (!handle) {
            this.handles.length = 0
        } else {
            ~pos && this.handles[type].splice(pos, 1)
        }
    }
    publish() {
        let type = Array.prototype.shift.call(arguments)
        this.handles[type].forEach(handle => {
            handle.apply(this, arguments)
        })
    }
}

const pub = new Pubsub()
pub.subscribe('a', function() {console.log('a', ...arguments)})
pub.publish('a', 1, 2, 3)
// a 1 2 3

Tags: Javascript JSON

Posted on Mon, 02 Dec 2019 20:08:41 -0500 by GreenCore