tzlib
Version:
Extension methods to premitive types
124 lines (123 loc) • 4.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("./util");
if (!Array.prototype.first) {
Array.prototype.first = function () {
if (this.length > 0) {
return this[0];
}
else {
throw new Error("Array has no elements");
}
};
}
if (!Array.prototype.clear) {
Array.prototype.clear = function () {
if (this.length > 0) {
this.splice(0, this.length);
}
else {
throw new Error("Array has no elements");
}
return this;
};
}
if (!Array.prototype.last) {
Array.prototype.last = function () {
if (this.length > 0) {
return this[this.length - 1];
}
else {
throw new Error("Array has no elements");
}
};
}
if (!Array.prototype.where) {
Array.prototype.where = function (predicate) {
let resultArray = new Array();
this.forEach((item) => {
if (predicate(item)) {
resultArray.push(item);
}
});
return resultArray;
};
}
if (!Array.prototype.addRange) {
Array.prototype.addRange = function (listToAdd) {
this.push(...listToAdd);
return this;
};
}
if (!Array.prototype.removeRange) {
Array.prototype.removeRange = function (index, range) {
this.splice(index, range);
return this;
};
}
if (!Array.prototype.insertAt) {
Array.prototype.insertAt = function (item, index) {
this.splice(index, 0, item);
return this;
};
}
if (!Array.prototype.getMatchCount) {
Array.prototype.getMatchCount = function (predicate) {
return this.filter(predicate).length;
};
}
if (!Array.prototype.strictSort) {
Array.prototype.strictSort = function () {
if (this.length > 1) {
const typeDetermine = typeof this[0];
switch (typeDetermine) {
case "string":
return this.sort();
case "number":
return this.sort(util_1.compare);
default:
throw new Error("'strictSort' works with 'number' and 'string'. For sorting array of Objects, use 'orderBy' function");
}
}
else {
throw new Error("Invalid or Insufficient items in Array");
}
};
}
if (!Array.prototype.orderBy) {
Array.prototype.orderBy = function (propertyExpression, asc = true) {
if (this.length > 1) {
const typeDetermine = typeof this[0];
if (typeDetermine === "object") {
const compareFunction = (ele1, ele2) => {
for (let i = 0; i < propertyExpression.length; i++) {
if (propertyExpression(ele1) > propertyExpression(ele2)) {
return asc ? 1 : -1;
}
if (propertyExpression(ele2) > propertyExpression(ele1)) {
return asc ? -1 : 1;
}
}
return 0;
};
this.forEach((arrayItem) => {
return this.sort(compareFunction);
});
return this;
}
else {
throw new Error("'orderBy' works with 'object' . For sorting array of string or number, use 'strictSort' function");
}
}
else {
throw new Error("Invalid or Insufficient items in Array");
}
};
if (!Array.prototype.removeDuplicate) {
Array.prototype.removeDuplicate = function (key) {
return Array.from(new Set(this.map(arrayIteam => arrayIteam[key]))).map(uniqueItem => {
return this.find(item => item[key] === uniqueItem);
});
};
}
}