github.com/hernad/nomad@v1.6.112/ui/app/utils/units.js (about) 1 /** 2 * Copyright (c) HashiCorp, Inc. 3 * SPDX-License-Identifier: MPL-2.0 4 */ 5 6 export const BYTES_UNITS = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; 7 export const HERTZ_UNITS = ['Hz', 'KHz', 'MHz', 'GHz', 'THz', 'PHz']; 8 9 const locale = window.navigator.locale || 'en'; 10 const decimalFormatter = new Intl.NumberFormat(locale, { 11 maximumFractionDigits: 2, 12 }); 13 const roundFormatter = new Intl.NumberFormat(locale, { 14 maximumFractionDigits: 0, 15 }); 16 17 const unitReducer = (number = 0, interval, units, maxUnit, startingUnit) => { 18 if (startingUnit && units.indexOf(startingUnit) !== -1) { 19 units = units.slice(units.indexOf(startingUnit)); 20 } 21 if (maxUnit && units.indexOf(maxUnit) !== -1) { 22 units = units.slice(0, units.indexOf(maxUnit) + 1); 23 } 24 25 // Reduce negative numbers by temporarily flipping them positive. 26 const negative = number < 0; 27 if (negative) { 28 number *= -1; 29 } 30 31 let unitIndex = 0; 32 while (number >= interval && unitIndex < units.length - 1) { 33 number /= interval; 34 unitIndex++; 35 } 36 37 if (negative) { 38 number *= -1; 39 } 40 return [number, units[unitIndex]]; 41 }; 42 43 export function reduceBytes(bytes = 0, maxUnitSize, startingUnitSize) { 44 return unitReducer(bytes, 1024, BYTES_UNITS, maxUnitSize, startingUnitSize); 45 } 46 47 export function reduceHertz(hertz = 0, maxUnitSize, startingUnitSize) { 48 return unitReducer(hertz, 1000, HERTZ_UNITS, maxUnitSize, startingUnitSize); 49 } 50 51 // General purpose formatters meant to reduce units as much 52 // as possible. 53 export function formatBytes(bytes, startingUnitSize) { 54 const [number, unit] = reduceBytes(bytes, null, startingUnitSize); 55 return `${decimalFormatter.format(number)} ${unit}`; 56 } 57 58 export function formatHertz(hertz, startingUnitSize) { 59 const [number, unit] = reduceHertz(hertz, null, startingUnitSize); 60 return `${decimalFormatter.format(number)} ${unit}`; 61 } 62 63 // Specialized formatters meant to reduce units to the resolution 64 // the scheduler and job specs operate at. 65 export function formatScheduledBytes(bytes, startingUnitSize) { 66 const [number, unit] = reduceBytes(bytes, 'MiB', startingUnitSize); 67 return `${roundFormatter.format(number)} ${unit}`; 68 } 69 70 export function formatScheduledHertz(hertz, startingUnitSize) { 71 const [number, unit] = reduceHertz(hertz, 'MHz', startingUnitSize); 72 return `${roundFormatter.format(number)} ${unit}`; 73 } 74 75 // Replaces the minus sign (−) with a hyphen (-). 76 // https://github.com/d3/d3-format/releases/tag/v2.0.0 77 export function replaceMinus(input) { 78 return input.replace('−', '-'); 79 }