Array Wrapper Classes
A couple wrapper classes that will help when dealing with simple arrays and arrays of objects.
by kshep92
JavaScript
var SimpleList = function(array) {
var _this = this;
var LIST_ERROR = "SimpleList is for simple variables. Consider using ObjectList for Object types."
if(array.length > 0 && typeof array[0] == "object") console.error(LIST_ERROR);
this.add = function(elm) {
if(typeof elm == "object") console.error(LIST_ERROR);
else array.push(elm);
}
this.addAll = function(elms) {
var newElms = [];
if(elms != undefined && Array.isArray(elms)) {
elms.map(function(elm) { array.push(elm); newElms.push(elm); });
} else console.error("Please enter a valid array.");
return newElms;
}
this.clear = function() { array = []; }
this.contains = function(elm) {
return this.indexOf(elm) > -1;
}
this.getAll = function() { return array; }
this.getAt = function(index) {
if(index < array.length && index > -1) return array[index];
else return undefined;
}
this.indexOf = function(elm) { return array.indexOf(elm); };
this.isEmpty = function() { return array.length == 0; }
this.remove = function(elm) {
var index = array.indexOf(elm);
if(index > -1) { array.splice(index, 1); return true; }
else return false;
};
this.size = function() { return array.length; }
}
/* Object List */
var ObjectList = function(array, idField) {
var id = idField == undefined ? "id" : idField;
var baseTempId = new Date().getTime();
var _this = this;
this.add = function(obj) {
//If the object does not have a id field, give it a temporary ID field
if(Object.keys(obj).indexOf(id) == -1) {
setId(obj);
}
array.push(obj);
return obj;
}
this.addAll = function(elms) {
var newElms = [];
if(elms != undefined && Array.isArray(elms)) {
elms.map(function(elm) { _this.add(elm); newElms.push(elm); });
return newElms;
} else {
console.error("Please enter a real array.");
return [];
}
}
this.clear = function() { array = []; }
...