본문 바로가기

Programming/Script

[Object] JavaScript Map

function JsMap(Delimitor) {
    this.Delimitor = (Delimitor == null ? "||" : Delimitor);
    this._MapClass = new ActiveXObject("Scripting.Dictionary");
    
    this.get = function(key) { return this._MapClass.exists(key) ? this._MapClass.item(key) : null; }
    this.getKey = function (value) {
        var keys = this.keys();
        var values = this.values();
        for (var i in values) {
            if (value == values[i]) return keys[i];
        }
        return "";
    }
    this.put = function(key, value) {
        var oldValue = this._MapClass.item(key);
        this._MapClass.item(key) = value;
        return value;
    }
    this.size = function() { return this._MapClass.count; }
    this.remove = function(key) {
        var value = this._MapClass.item(key);
        this._MapClass.remove(key);
        return value;
    }
    this.clear = function() {
        this._MapClass.removeAll();
    }
    this.keys = function() {
        return this._MapClass.keys().toArray();
    }
    this.values = function() {
        return this._MapClass.items().toArray();
    }
    this.containsKey = function(key) {
        return this._MapClass.exists(key);
    }
    this.containsValue = function(value) {
        var values = this.values();
        for (var i in values) {
            if (value == values[i]) {
                return true;
            }
        }
        return false;
    }
    this.isEmpty = function() { return this.size() <= 0;}
    this.putAll = function(map) {
        if (!(map instanceof Map)) {
            throw new Error(0, "Type Error : Map.putAll(Map)");
        }
        var keys = map.keys();
        for (var i in keys) {
            this.put(keys[i], map.get(keys[i]));
        }
        return this;
    }
    
    this.toString = function(separator) {
        var keys = this.keys();
        var result = "";
        separator = separator == null ? "&" : separator;
        for (var i in keys) {
            result += (keys[i] + this.Delimitor + this._MapClass.item(keys[i]));
            if (i < this.size() - 1) {
                result += separator;
            }
        }
        return result;
    }
}