数据结构与算法之字典和散列表

//字典
        function Dictionary(){
            this.items = {};
        }

        Dictionary.prototype={
            set:function(key,value){
                this.items[key]=value;
            },
            remove:function(key){
                if(this.has(key)){
                    delete items[key];
                    return true;
                }
                return false;
            },
            has:function(key){
                //key是否items对象的一个属性
                return key in this.items;
            },
            get:function(key){
                return this.has(key)?this.items[key]:undefined;
            },
            clear:function(){
                this.items={};
            },
            size:function(){
                return Object.keys(this.items).length;
            },
            keys:function(){
                var keys = [];
                for(var k in this.items){
                    if(this.has(k)){
                        keys.push(k);
                    }
                }
                return keys;
            },
            values:function(){
                var values = [];
                for(var k in this.items){
                    if(this.has(k)){
                        values.push(this.items[k]);
                    }
                }
                return values;
            }
        };

        //散列表
        function HashTable(){
            this.table=[];
        }

        HashTable.prototype={
            loseloseHashCode:function(key){
                var hash = 0;
                for(var i =0;i<key.length;i++){
                    hash  += key.charCodeAt(i);
                }
                return hash % 37;
            },
            put:function(key,value){
                var position = this.loseloseHashCode(key);
                this.table[position] = value;
            },
            get:function(key){
                return this.table[this.loseloseHashCode(key)];
            },
            remove:function(key){
                this.table[this.loseloseHashCode(key)] = undefined;
            }
        };
    
原文地址:https://www.cnblogs.com/kerryw/p/8339819.html