Is there a hashmap library for JavaScript?

后端 未结 8 1725
抹茶落季
抹茶落季 2021-02-14 10:35

In JavaScript, all Objects act a bit like hashmaps. However, the keys to these hashmaps must be strings. If they\'re not, they\'re converted with toString(). Tha

8条回答
  •  无人共我
    2021-02-14 11:07

    Here's a quick proof-of-concept...

    I've hardly tested it at all, and I'm certain that there will be corner-cases that it can't deal with.

    Performance will be hideously inefficient because the __createHash function needs to recurse through the members of any objects and then sort them, in order to generate a "hash" that meets your requirements.

    HashMap = function() {
        this.get = function(key) {
            var hash = this.__createHash(key);
            return this.__map[hash];
        };
    
        this.set = function(key, value) {
            var hash = this.__createHash(key);
            this.__map[hash] = value;
        };
    
        this.__createHash = function(key) {
            switch (typeof key) {
                case 'function':
                    return 'function';
    
                case 'undefined':
                    return 'undefined';
    
                case 'string':
                    return '"' + key.replace('"', '""') + '"';
    
                case 'object':
                    if (!key) {
                        return 'null';
                    }
    
                    switch (Object.prototype.toString.apply(key)) {
                        case '[object Array]':
                            var elements = [];
                            for (var i = 0; i < key.length; i++) {
                                elements.push(this.__createHash(key[i]));
                            }
                            return '[' + elements.join(',') + ']';
    
                        case '[object Date]':
                            return '#' + key.getUTCFullYear().toString()
                                       + (key.getUTCMonth() + 1).toString()
                                       + key.getUTCDate().toString()
                                       + key.getUTCHours().toString()
                                       + key.getUTCMinutes().toString()
                                       + key.getUTCSeconds().toString() + '#';
    
                        default:
                            var members = [];
                            for (var m in key) {
                                members.push(m + '=' + this.__createHash(key[m]));
                            }
                            members.sort();
                            return '{' + members.join(',') + '}';
                    }
    
                default:
                    return key.toString();
            }
        };
    
        this.__map = {};
    }
    

提交回复
热议问题