@etsoo/shared
Version:
TypeScript shared utilities and functions
103 lines (102 loc) • 3.29 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArrayUtils = void 0;
const lodash_isequal_1 = __importDefault(require("lodash.isequal"));
Array.prototype.different = function (target, round) {
return ArrayUtils.differences(this, target, round);
};
Array.prototype.toUnique = function () {
if (this.length === 0 || typeof this[0] !== "object")
return Array.from(new Set(this));
const newArray = [];
this.forEach((item) => {
if (newArray.some((newItem) => (0, lodash_isequal_1.default)(item, newItem)))
return;
newArray.push(item);
});
return newArray;
};
Array.prototype.max = function (field) {
if (field == null) {
return Math.max(...this);
}
return Math.max(...this.map((item) => item[field]));
};
Array.prototype.maxItem = function (field) {
if (this.length === 0)
return undefined;
return this.reduce((prev, curr) => (prev[field] > curr[field] ? prev : curr));
};
Array.prototype.min = function (field) {
if (field == null) {
return Math.min(...this);
}
return Math.min(...this.map((item) => item[field]));
};
Array.prototype.minItem = function (field) {
if (this.length === 0)
return undefined;
return this.reduce((prev, curr) => (prev[field] < curr[field] ? prev : curr));
};
Array.prototype.remove = function (...items) {
const funs = [];
const results = [];
items.forEach((item) => {
if (typeof item === "function") {
funs.push(item);
}
else {
// For object items, should be removed by reference, not by value
const index = this.indexOf(item);
if (index >= 0)
results.push(...this.splice(index, 1));
}
});
if (funs.length > 0) {
// Reduce check loops for performance
for (let i = this.length - 1; i >= 0; i--) {
if (funs.some((fun) => fun(this[i])))
results.push(...this.splice(i, 1));
}
}
return results;
};
Array.prototype.sortByProperty = function (property, values) {
return this.sort((a, b) => {
const ai = values.indexOf(a[property]);
const bi = values.indexOf(b[property]);
if (ai === bi)
return 0;
if (ai < 0 || bi < 0)
return bi === 0 ? 1 : bi;
return ai - bi;
});
};
Array.prototype.sum = function (field) {
if (field == null) {
return this.reduce((total, num) => total + num, 0);
}
return this.reduce((total, item) => total + item[field], 0);
};
/**
* Array Utilities
*/
var ArrayUtils;
(function (ArrayUtils) {
/**
* Array 1 items do not exist in Array 2 or reverse match
* @param a1 Array 1
* @param a2 Array 2
* @param round A round for both matches
*/
function differences(a1, a2, round) {
const diff = a1.filter((x) => !a2.includes(x));
if (round)
return [...diff, ...a2.filter((x) => !a1.includes(x))];
return diff;
}
ArrayUtils.differences = differences;
})(ArrayUtils || (exports.ArrayUtils = ArrayUtils = {}));