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(arr) {
var array = arr == undefined ? [] : arr;
this.add = function(elm) {
if(Array.isArray(elm)) {
elm.map(function(current) { array.push(current); });
} else array.push(elm);
}
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; }
}
var ObjectList = function(arr) {
var array = arr == undefined ? [] : arr;
this.add = function(elm) {
if(Array.isArray(elm)) {
elm.map(function(current) { array.push(current); });
} else array.push(elm);
}
this.clear = function() { array = []; }
this.contains = function(obj) {
return this.indexOf(obj) > -1;
}
this.find = function(obj, field) {
var index = this.indexOf(obj, field);
if(index > -1) return array[index];
else return undefined;
}
this.getAll = function() { return array; }
this.getAt = function(index) {
if(index < array.length && index > -1) return array[index];
else return undefined;
}
this.indexOf = function(obj, field) {
var _field = field == undefined ? Object.keys(obj)[0] : field;
var _index = -1;
array.map(function(current, index) {
if(current[_field] == obj[_field]) _index = index;
})
return _index;
}
this.isEmpty = function() { return array.length == 0; }
this.remove = function(obj) {
var index = this.indexOf(obj);
if(index > -1) {
array.splice(index, 1);
...