UNPKG

topkat-utils

Version:

A comprehensive collection of TypeScript/JavaScript utility functions for common programming tasks. Includes validation, object manipulation, date handling, string formatting, and more. Zero dependencies, fully typed, and optimized for performance.

56 lines 2.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.minMax = exports.pad = exports.moyenne = exports.sumArray = exports.randomMultipleOf = exports.random = exports.isBetween = exports.round2 = exports.round = void 0; //---------------------------------------- // MATH UTILS //---------------------------------------- const isset_1 = require("./isset"); /** Round with custom number of decimals (default:0) */ function round(number, decimals = 0) { return Math.round((typeof number === 'number' ? number : parseFloat(number)) * Math.pow(10, decimals)) / Math.pow(10, decimals); } exports.round = round; /** Round with custom number of decimals (default:2) */ function round2(number, decimals = 2, format = 'string') { return (format === 'string' ? Number(number).toFixed(decimals) : round(number, decimals)); } exports.round2 = round2; /** Is number between two numbers (including those numbers) */ function isBetween(number, min, max, inclusive = true) { return inclusive ? number <= max && number >= min : number < max && number > min; } exports.isBetween = isBetween; /** Random number between two values with 0 decimals by default */ function random(nb1, nb2, nbOfDecimals = 0) { return round(Math.random() * (nb2 - nb1) + nb1, nbOfDecimals); } exports.random = random; /** Random multiple of a number between two values */ function randomMultipleOf(multiple, nb1, nb2) { if (multiple === 0) multiple = 1; let randomNumber = Math.random() * (nb2 - nb1) + nb1; randomNumber = Math.round(randomNumber / multiple) * multiple; return randomNumber < 1 ? randomNumber = multiple : randomNumber; } exports.randomMultipleOf = randomMultipleOf; /** Sum all values of an array, all values MUST be numbers */ function sumArray(array) { return array.filter(item => typeof item === 'number').reduce((sum, val) => (0, isset_1.isset)(val) ? val + sum : sum, 0); } exports.sumArray = sumArray; /** Moyenne / average between array of values * @param {Number} round number of decimals to keep. Default:2 */ function moyenne(array, nbOfDecimals = 2) { return round(sumArray(array) / array.length, nbOfDecimals); } exports.moyenne = moyenne; /** length default 2, shortcut for 1 to 01 */ function pad(numberOrStr, length = 2) { return ('' + numberOrStr).padStart(length, '0'); } exports.pad = pad; /** return the number or the closest number of the range * * nb min max => returns * * 7 5 10 => 7 // in the range * * 2 5 10 => 5 // below the min value * * 99 5 10 => 10// above the max value */ function minMax(nb, min, max) { return Math.max(min, Math.min(nb, max)); } exports.minMax = minMax; //# sourceMappingURL=math-utils.js.map