@qudtlib/core
Version:
Data model for QUDTLib
102 lines (101 loc) • 3.33 kB
JavaScript
import { Decimal } from "decimal.js";
export function getLastIriElement(iri) {
return iri.replaceAll(/.+\/([^\/]+)/g, "$1");
}
export const BooleanComparator = (left, right) => (left === right ? 0 : left ? 1 : -1);
export const NumberComparator = (left, right) => (left < right ? -1 : left == right ? 0 : 1);
export const StringComparator = (left, right) => (left < right ? -1 : left === right ? 0 : 1);
export function compareUsingEquals(a, b) {
return a.equals(b);
}
export function arrayDeduplicate(arr, cmp = (a, b) => a === b) {
if (!arr || !arr.length || arr.length === 0) {
return arr;
}
return arr.reduce((prev, cur) => prev.some((p) => cmp(p, cur)) ? prev : [...prev, cur], []);
}
export function arrayEquals(left, right, cmp = (a, b) => a === b) {
return (!!left &&
!!right &&
left.length === right.length &&
left.every((e, i) => cmp(e, right[i])));
}
export function arrayEqualsIgnoreOrdering(left, right, cmp = (a, b) => a === b) {
if (!!left && !!right && left.length === right.length) {
const unmatched = Array.from({ length: left.length }, (v, i) => i);
outer: for (let i = 0; i < left.length; i++) {
for (let j = 0; j < unmatched.length; j++) {
if (cmp(left[i], right[unmatched[j]])) {
unmatched.splice(j, 1);
continue outer;
}
}
return false;
}
return true;
}
return false;
}
export function arrayCountEqualElements(left, right, cmp = (a, b) => a === b) {
if (!!left && !!right) {
const unmatched = Array.from({ length: left.length }, (v, i) => i);
outer: for (let i = 0; i < left.length; i++) {
for (let j = 0; j < unmatched.length; j++) {
if (cmp(left[i], right[unmatched[j]])) {
unmatched.splice(j, 1);
continue outer;
}
}
}
return left.length - unmatched.length;
}
return 0;
}
export function arrayMin(arr, cmp) {
if (!arr || !arr?.length) {
throw "array is undefined or empty";
}
let min = undefined;
for (const elem of arr) {
if (typeof min === "undefined" || cmp(min, elem) > 0) {
min = elem;
}
}
if (typeof min === "undefined") {
throw "no minimum found";
}
return min;
}
export function arrayMax(arr, cmp) {
return arrayMin(arr, (left, right) => -1 * cmp(left, right));
}
export function arrayContains(arr, toFind, cmp = (a, b) => a === b) {
if (!arr) {
throw "array is undefined";
}
for (const elem of arr) {
if (cmp(elem, toFind)) {
return true;
}
}
return false;
}
export function checkInteger(arg, argName) {
if (!Number.isInteger(arg)) {
throw `${argName} must be integer, ${arg} (type ${typeof arg}) is not`;
}
}
export function findInIterable(iterable, predicate) {
for (const elem of iterable) {
if (predicate(elem)) {
return elem;
}
}
return undefined;
}
export function isNullish(val) {
return typeof val === "undefined" || val === null;
}
export const ONE = new Decimal("1");
export const ZERO = new Decimal("0");
//# sourceMappingURL=utils.js.map