Files
kit/assets/collection/collection.js
T
2021-09-29 12:05:44 +03:00

74 lines
2.1 KiB
JavaScript

/** @module collection */
kit.PluginManager.register('collection',function(module, exports, require, global) {
function valueEx(value) {
if(typeof value === 'function') {
return value();
}
return value;
}
function uniqueId (length = 32, firstLetter = true) {
var idStr = '';
if(length < 1) return idStr;
if(firstLetter) {
length && (idStr = (Math.floor((Math.random() * 25)) + 10).toString(36));
if (length === 1) return idStr;
}
do {
idStr += (Math.floor((Math.random() * 35))).toString(36);
} while (idStr.length < length);
return (idStr);
};
var ArrayCollection = function (data){
this.data = data;
};
ArrayCollection.prototype.all = function () {
return this.data;
};
ArrayCollection.prototype.put = function (key, value) {
this.data[key] = value;
};
ArrayCollection.prototype.push = function (value) {
this.data.push(value);
};
ArrayCollection.prototype.get = function (key, defValue = undefined) {
if(this.data.hasOwnProperty(key)) {
return this.data[key];
}
return valueEx(defValue);
};
ArrayCollection.prototype.has = function (key) {
return this.data.hasOwnProperty(key);
};
var ObjectCollection = function (data){
this.data = data;
};
ObjectCollection.prototype.all = ArrayCollection.prototype.all;
ObjectCollection.prototype.put = ArrayCollection.prototype.put;
ObjectCollection.prototype.push = function (value) {
this.data[uniqueId(8)] = value;
};
ObjectCollection.prototype.get = ArrayCollection.prototype.get;
ObjectCollection.prototype.has = ArrayCollection.prototype.has;
/**
* @memberof kitCore
* @instance
*/
var Collection = function (data) {
if(typeof data === 'object') {
return new ObjectCollection(data);
}
if(Array.isArray(data)) {
return new ArrayCollection(data);
}
return new ArrayCollection([data]);
}
return module.exports = Collection;
});