Javascript - A Set class

    // 9.6.1 A Set Class
    function Set() {
        this.values = {};
        this.n = 0;
        this.add.apply(this, arguments);
    }

    Set.prototype.add = function() {
        for(var i = 0 ; i < arguments.length; i++) {
            var val = arguments[i];
            var str = Set._v2s(val);
            if(!this.values.hasOwnProperty(str)) {
                this.values[str] = val;
                this.n++;
            }
        }
        return this;
    }

    Set.prototype.remove = function() {
        for(var i = 0; i < arguments.length; i++) {
            var str = Set._v2s(arguments[i]);
            if(this.values.hasOwnProperty(str)) {
                delete this.values[str];
                this.n--;
            }
        }
        return this;
    }

    Set.prototype.contains = function(value) {
        return this.values.hasOwnProperty(Set._v2s(value));
    }

    Set.prototype.size = function() {
        return this.n;
    }

    Set._v2s = function(val) {
        switch(val) {
            case undefined: return 'u';
            case null: return 'n';
            case true: return 't';
            case false: return 'f';
            default: switch(typeof val){
                case 'number': return '#' + val;
                case 'string': return '"' + val;
                default: return '@' + objectId(val);
            }
        }

        function objectId(o) {
            var prop = "|**objectid**|";
            if(!o.hasOwnProperty(prop))
                o[prop] = Set._v2s.next++;
            return o[prop];
        }
    };

    class Animal {
        constructor(name) {
            this.name = name;
        }
        walk() {
            console.log(this.name + " is walking...");
        }
    }

    Set._v2s.next = 100;
    
    var anAnimal = new Animal("pp");
    var aSet = new Set();
    aSet.add("hello", anAnimal, [1,2,3], false, true, false, 12, 13, 3.3, 4.4);
    var str = aSet.toString();
    aSet.remove(true, false, 12, anAnimal);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章