JS手写一个map的数据结构

63 阅读1分钟
let OrderedMap = function(){
    this.cache = []
}
OrderedMap.prototype.set = function(key,value){
    if(this.cache[key]){
        delete this.cache[key]
        this.cache[key] = []
    }else{
        this.cache[key] = []
    }
    this.cache[key] = value
}
OrderedMap.prototype.get = function(key){
    if(this.cache[key]){
        return this.cache[key]
    }else{
        return -1
    }
}
OrderedMap.prototype.getIndex = function(item){
    let size = 0
    for(let key in this.cache){
        if(this.cache[key] == item){
            return ++size
        }
        size++;
    }
    return -1
}


let order = new OrderedMap()
order.set('a',1)
order.set('b',2)
order.set('a',4)
console.log(order.get('a')) //4
console.log(order.getIndex(4)) //2