Modules – Exercise (RMP)

by Shane Porter

JavaScript

/**
 * Modules – Exercise (RMP)
 * 
 * Use the Revealing Module Pattern to encapsulate logic into re-usable modules
 * 
 * 1. convert Item and Collection objects into modules
 * 2. import them into App module
 * 3. use same tests as previous exercise
 * 4. might be easier to fork your previous exercise solution and modify
 */

var Collection = (function () {
    function Collection(id) {
    this.id = id;
    this.items = [];
}

Collection.prototype.add = function(Item){
	var totalNow = this.items.push(Item);
}

Collection.prototype.remove = function(Item){
	var pos = this.items.indexOf(Item);
    this.items.splice(pos, 1);
}

Collection.prototype.size = function(){
	return this.items.length;
}

Collection.prototype.contains = function(Item){
	return this.items.indexOf(Item) !== -1; 
}

Collection.prototype.filter = function (fn) {
    return this.items.filter(fn);
};
    
   return Collection;
}());


var Item = (function () {
    function Item(id) {
    this.id = id;
    this.data = new Collection(this.id + 'Data');
}

Item.prototype.getById = function (id) {
    return this.data.filter(function (item) {
        return item.id === id;
    }).pop();
}

Item.prototype.get = function (key) {
    var item = this.getById(key);
    return item ? item.value : undefined;
};

Item.prototype.set = function (key, value) {
    var item = this.getById(key);
    if (!item) {
        item = {
            id: key,
            value: value
        };
        this.data.add(item);
    }
    item.value = value;
};
    return Item;
}());

var AppModule = (function ( Collection, Item ) {
    return {
        Collection: Collection,
        Item: Item
    };
}( Collection, Item ));

var collection1 = new AppModule.Collection('collection1');
var collection1 = new AppModule.Collection('collection1');
var collection2 = new AppModule.Collection('collection2');
var item1 = new AppModule.Item('item1');
var item2 = new AppModule.Item('item2');
var item3 = new...