UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

73 lines (72 loc) 2.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculatePercentage = calculatePercentage; const basics_1 = require("./basics"); const guards_1 = require("./guards"); function calculatePercentage(options) { const { roundTo = 3 } = options; const _roundNumber = (num) => { const factor = 10 ** roundTo; return Math.round(num * factor) / factor; }; switch (options?.mode) { case 'get-percent': { const { part, total } = options; if ((0, guards_1.areInvalidNumbers)(part, total) || total === 0) { return NaN; } return _roundNumber((part / total) * 100); } case 'get-value': { const { percentage, total } = options; if ((0, guards_1.areInvalidNumbers)(percentage, total) || total === 0) { return NaN; } return _roundNumber((percentage / 100) * total); } case 'get-original': { const { percentage, value } = options; if ((0, guards_1.areInvalidNumbers)(percentage, value) || percentage === 0) { return NaN; } return _roundNumber((value / percentage) * 100); } case 'get-change-percent': { const { oldValue, newValue } = options; if ((0, guards_1.areInvalidNumbers)(oldValue, newValue) || oldValue === 0) { return NaN; } const change = ((newValue - oldValue) / oldValue) * 100; return _roundNumber(change); } case 'apply-percent-change': { const { baseValue, percentage } = options; if ((0, guards_1.areInvalidNumbers)(baseValue, percentage)) { return NaN; } const value = baseValue * (1 + percentage / 100); return _roundNumber(value); } case 'get-percent-difference': { const { value1, value2 } = options; if ((0, guards_1.areInvalidNumbers)(value1, value2)) { return NaN; } const avg = (0, basics_1.getAverage)(value1, value2); if (avg === 0) { return NaN; } const diff = (Math.abs(value1 - value2) / avg) * 100; return _roundNumber(diff); } case 'inverse-percent': { const { part, total } = options; if ((0, guards_1.areInvalidNumbers)(part, total) || part === 0) { return NaN; } return _roundNumber((total / part) * 100); } default: return NaN; } }