UNPKG

s9s-objects

Version:

Global object container, used across projects

93 lines (82 loc) 2.09 kB
'use strict'; exports = module.exports = AbstractCollection; const AbstractArray = require(__dirname + '/AbstractArray'); /** * @constructor * @extends {AbstractArray} * @abstract */ function AbstractCollection() { AbstractArray.apply(this, arguments); } /** * @type {Array} */ AbstractCollection.prototype = new AbstractArray(); /** * @type {AbstractCollection} */ AbstractCollection.prototype.constructor = AbstractCollection; /** * @type {null} * @protected * @const */ AbstractCollection.prototype.objectConstructor = null; /** * @param data * @param Constructor */ AbstractCollection.prototype.applyData = function (data, Constructor) { data = data || []; for (var i = 0; i < data.length; i++) { if (data[i] instanceof Constructor) { this.push(data[i]); } else { this.push(new Constructor(data[i])); } } }; /** * Override push method to check for object instances * @returns {Number} */ AbstractCollection.prototype.push = function () { if (!isnull(this.objectConstructor)) { for (var i = 0; i < arguments.length; i++) { if (!(arguments[i] instanceof this.objectConstructor)) { throw new TypeError(ErrorText.AbstractCollectionBadType.sprintf(arguments[i], this.objectConstructor)); } } } return Array.prototype.push.apply(this, arguments); }; /** * Returns an object value by key and value * @param key * @param value * @returns {null|{}|AbstractObject|*} */ AbstractCollection.prototype.getBy = function (key, value) { for (var i = 0; i < this.size(); i++) { if (this[i][key] == value) { return this[i]; } } return null; }; /** * @param Constructor * @param key * @param value * @returns {AbstractCollection|*} */ AbstractCollection.prototype.getListBy = function (Constructor, key, value) { var list = new Constructor(); for (var i = 0; i < this.size(); i++) { if (this[i][key] == value) { list.push(this[i]); } } return list; };