OO – Exercise

by manu troiani

JavaScript

/**
 * OO – Exercise
 * 
 * 1. Collection object
 *   a. Internal data should not be accessible, except through exposed methods
 *   b. It should have a "add" method, which accepts an Item instance
 *   c. It should have a "remove" method, which removes the provided Item
 *   d. It should have a "size" method, which returns the size of internal data
 *   e. It should have a "contains" method, which returns a boolean indicating 
 *      whether the Item exists in internal data */
 
var Collection = (function () {

    var _name;
    var data = [];

    // Define the Student constructor
    function Collection(name) {
       data = new Array();
    };
    
    Collection.prototype.add = function (item) {
        data.push(item);
    };
    
    Collection.prototype.remove = function (item) {
        var pos = this.data.indexOf(item);
        if ( pos > -1 ) 
        	data.splice( pos, 1 );
        
    };
    Collection.prototype.size = function() {
       		 return data.length;
      
    };
    
    Collection.prototype.contains = function (item) {
        	return ( data.indexOf(item) !== -1 );
    };

    
    
    Collection.prototype.setName = function (name) {
        _name = name;
    };
    Collection.prototype.getName = function () {
        return _name;
    };

    return Collection;

}());



/*
 
 * 2. Item object
 *   a. Internal data should not be accessible, except through exposed methods
 *   b. It should have a "get" method that accepts a property name
 *   c. It should have a "set" method that accepts a property name and value
 
 */

/*
function Item(id) {
    // implement me
    
    // to be able to have protoype methods that can access _name,
    // they have to be defined within the constructor's scope
    this.setName = function (name) {
        _name = name;
    };
    this.getName = function () {
        return _name;
    };

}
*/


// via IIFE
var Item = (function () {

    var _items = [];
	
    function Item(){
        this._item = new...