@dvcol/common-utils
Version:
Typescript library for common utility functions and constants
38 lines (29 loc) • 2.21 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// lib/common/utils/math.utils.ts
var arrayMax = (array, prop, filter) => _optionalChain([array, 'optionalAccess', _ => _.length]) ? _optionalChain([array, 'optionalAccess', _2 => _2.reduce, 'call', _3 => _3((prev, current) => {
if (filter && !filter(current)) return prev;
if (prev[prop] === void 0 || current[prop] !== void 0 && current[prop] > prev[prop]) {
return current;
}
return prev;
})]) : void 0;
var findClosestMatch = (value, array) => {
if (!_optionalChain([array, 'optionalAccess', _4 => _4.length])) return "original";
let closestMatch = array[0];
let minDifference = Math.abs(value - parseInt(array[0].substring(1), 10));
for (let i = 1; i < array.length; i += 1) {
const currentValue = parseInt(array[i].substring(1), 10);
const difference = Math.abs(value - currentValue);
if (difference < minDifference) {
minDifference = difference;
closestMatch = array[i];
}
}
if (!closestMatch) return "original";
if (Math.abs(parseInt(closestMatch.substring(1), 10)) * 2 < Math.abs(value)) return "original";
return closestMatch;
};
var clamp = (val, min, max) => Math.min(Math.max(val, min), max);
var randomInt = (min = 0, max = 100) => Math.floor(Math.random() * (max - min + 1)) + min;
var round = (value, precision = 0) => Math.round(value * 10 ** precision) / 10 ** precision;
var percent = (value, total = 100, precision = 2) => round(value / total * 100, precision);
exports.arrayMax = arrayMax; exports.findClosestMatch = findClosestMatch; exports.clamp = clamp; exports.randomInt = randomInt; exports.round = round; exports.percent = percent;