JavaScript hashmap equivalent

前端 未结 17 1241
执笔经年
执笔经年 2020-11-22 13:23

As made clear in update 3 on this answer, this notation:

var hash = {};
hash[X]

does not actually hash the object X; it actually

17条回答
  •  心在旅途
    2020-11-22 14:26

    Unfortunately, none of the previous answers were good for my case: different key objects may have the same hash code. Therefore, I wrote a simple Java-like HashMap version:

    function HashMap() {
        this.buckets = {};
    }
    
    HashMap.prototype.put = function(key, value) {
        var hashCode = key.hashCode();
        var bucket = this.buckets[hashCode];
        if (!bucket) {
            bucket = new Array();
            this.buckets[hashCode] = bucket;
        }
        for (var i = 0; i < bucket.length; ++i) {
            if (bucket[i].key.equals(key)) {
                bucket[i].value = value;
                return;
            }
        }
        bucket.push({ key: key, value: value });
    }
    
    HashMap.prototype.get = function(key) {
        var hashCode = key.hashCode();
        var bucket = this.buckets[hashCode];
        if (!bucket) {
            return null;
        }
        for (var i = 0; i < bucket.length; ++i) {
            if (bucket[i].key.equals(key)) {
                return bucket[i].value;
            }
        }
    }
    
    HashMap.prototype.keys = function() {
        var keys = new Array();
        for (var hashKey in this.buckets) {
            var bucket = this.buckets[hashKey];
            for (var i = 0; i < bucket.length; ++i) {
                keys.push(bucket[i].key);
            }
        }
        return keys;
    }
    
    HashMap.prototype.values = function() {
        var values = new Array();
        for (var hashKey in this.buckets) {
            var bucket = this.buckets[hashKey];
            for (var i = 0; i < bucket.length; ++i) {
                values.push(bucket[i].value);
            }
        }
        return values;
    }
    

    Note: key objects must "implement" the hashCode() and equals() methods.

提交回复
热议问题