手動模擬實現Map

基於hash算法 表 鏈表實現模擬

拿到對應的key值----> 轉化得到hash值---->對應到相對的表的位置(這個其實使用一個數組實現) ----> 在對應的位置對鏈表進行操作

function myMap() {
    this.bucketLength = 8
    this.bucket = []
    this.init()
}

myMap.prototype.init = function() {
    this.bucket = new Array(this.bucketLength)
    for (var i = 0; i < this.bucketLength; i++) {
        this.bucket[i] = {
            type: 'bucket_' + i,
            next: null
        }
    }
}

myMap.prototype.makeHash = function(key) {
    let hash = 0
    if (typeof key === 'string') {
        for (let i = 0; i < 3; i++) {
            hash += key[i] ? key[i].charCodeAt(0) : 0
        }
    } else {
        if (typeof key === 'object') {
            hash = 1
        } else if (typeof key === 'number') {
            hash = Object.is(key, NaN) ? 0 : key
        } else if (typeof key === 'boolean') {
            hash = +key
        } else {
            hash = 2
        }
    }
    return hash % 8
}

myMap.prototype.set = function(key, value) {
    let hash = this.makeHash(key)
    let oTempBucket = this.bucket[hash]
    while (oTempBucket.next) {
        if (oTempBucket.next.key === key) {
            oTempBucket.next.value = value
            return
        } else {
            oTempBucket = oTempBucket.next
        }
    }
    oTempBucket.next = {
        key: key,
        value: value,
        next: null
    }

}

myMap.prototype.get = function(key) {
    let hash = this.makeHash(key)
    let oTempBucket = this.bucket[hash]
    while (oTempBucket.next) {
        if (oTempBucket.next.key === key) {
            return oTempBucket.next.value
        } else {
            oTempBucket = oTempBucket.next
        }
    }
    return undefined
}

myMap.prototype.delete = function(key) {
    let hash = this.makeHash(key)
    let oTempBucket = this.bucket[hash]
    while (oTempBucket.next) {
        if (oTempBucket.next.key === key) {
            oTempBucket.next = oTempBucket.next.next
            return true
        } else {
            oTempBucket = oTempBucket.next
        }
    }
    return false
}

myMap.prototype.has = function(key) {
    let hash = this.makeHash(key)
    let oTempBucket = this.bucket[hash]
    while (oTempBucket.next) {
        if (oTempBucket.next.key === key) {
            return true
        } else {
            oTempBucket = oTempBucket.next
        }
    }
    return false
}

myMap.prototype.clear = function() {
    this.init()
}

let oM = new myMap()
let obj = {}
oM.set('name', 'chen')
oM.set(obj, 'obj')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章