Javescript基础api实现原理

Math

1.pow

function pow(m, n) {
    if (n === 1) return m;

    if (n % 2 === 0) {
        return p(m, n / 2) * p(m, n / 2)
    } else {
        var newN = parseInt(n / 2)
        return p(m, newN) * p(m, newN) * m
    }
}

2.max

function max() {
    var args = Array.prototype.slice.call(arguments)
    function deep(arr) {
        if (arr.length === 2) {
            if (arr[0] > arr[1]) {
                return arr[0]
            } else {
                return arr[1]
            }
        }
        if (arr.length === 1) {
            return arr[0]
        }
        var mid = parseInt(arr.length / 2)
        var l = arr.slice(0, mid)
        var r = arr.slice(mid, arr.length)
        return deep(l) > deep(r) ? deep(l) : deep(r)
    }
    return deep(args)
}

3.min

function min() {
    var args = Array.prototype.slice.call(arguments)

    function deep(arr) {
        if (arr.length === 2) {
            if (arr[0] < arr[1]) {
                return arr[0]
            } else {
                return arr[1]
            }
        }
        if (arr.length === 1) {
            return arr[0]
        }
        var mid = parseInt(arr.length / 2)
        var l = arr.slice(0, mid)
        var r = arr.slice(mid, arr.length)
        return deep(l) > deep(r) ? deep(r) : deep(l)
    }
    return deep(args)
}

 原型链Api

instanceOf

function inst(ins, Fn) {
    insP = ins.__proto__
    fnP = Fn.prototype

    while (1) {
        if (insP === null) return false
        if (insP === fnP) return false
        insP = insP.__proto__
    }
}

 

上一篇:长链剖分O(nlogn)-O(1)求K级祖先


下一篇:element ui plus自定义样式