JSは簡単なクラスSetのデータ構造を実現します.

5502 ワード

作成
//              id
var Set = function () {
    //  this.               
    this.items = new Array(); //        Array
    this.size = 0; // Array   
    //     , id   ,   
    this.add = function (value) {
        if (value.id == undefined) {
            console.log("element id must be included.");
            return
        }
        if (!this.contains(value.id)) {
            this.items.push(value);
            this.size++;
        }
        return this;
    }
    //          
    this.contains = function (id) {
        for (var key in this.items) {
            if (this.items[key].id === id) {
                return true;
            }
        }
        return false;
    }
    //   id    
    this.get = function (id) {
        for (var key in this.items) {
            if (this.items[key].id === id) {
                return this.items[key];
            }
        }
        return null;
    }
    //   id    
    this.remove = function (id) {
        for (var key in this.items) {
            if (this.items[key].id === id) {
                delete this.items[key];
                this.size--;
            }
        }
    }
}
使用
//                    
var User = function (id, name) {
    this.id = id; //   id    
    this.name = name;
}

var set = new Set();
set.add(new User(1, 'ndd'));
set.add(new User(2, 'ndd'));
set.add(new User(2, 'ndd')); //          ,  id=2   

console.log(set);
console.log(set.size);
console.log(set.get(1));

set.remove(1); //   id=1   
console.log(set);
console.log(set.size);
console.log(set.get(1));