mirror of
https://github.com/Graylog2/graylog2-server.git
synced 2026-03-13 09:32:21 +08:00
103 lines
2.7 KiB
TypeScript
103 lines
2.7 KiB
TypeScript
/*
|
|
* Copyright (C) 2020 Graylog, Inc.
|
|
*
|
|
* This program is free software: you can redistribute it and/or modify
|
|
* it under the terms of the Server Side Public License, version 1,
|
|
* as published by MongoDB, Inc.
|
|
*
|
|
* This program is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* Server Side Public License for more details.
|
|
*
|
|
* You should have received a copy of the Server Side Public License
|
|
* along with this program. If not, see
|
|
* <http://www.mongodb.com/licensing/server-side-public-license>.
|
|
*/
|
|
import numeral from 'numeral';
|
|
|
|
type NumberInput = number | string;
|
|
|
|
const NumberUtils = {
|
|
JAVA_INTEGER_MIN_VALUE: 2 ** 31 * -1,
|
|
JAVA_INTEGER_MAX_VALUE: 2 ** 31 - 1,
|
|
BYTES_PER_GB: 1_000_000_000 as const,
|
|
normalizeNumber(number: NumberInput): number {
|
|
switch (number) {
|
|
case 'NaN':
|
|
return NaN;
|
|
case 'Infinity':
|
|
return Number.MAX_VALUE;
|
|
case '-Infinity':
|
|
return Number.MIN_VALUE;
|
|
default:
|
|
return Number(number);
|
|
}
|
|
},
|
|
normalizeGraphNumber(number: NumberInput): number {
|
|
switch (number) {
|
|
case 'NaN':
|
|
case 'Infinity':
|
|
case '-Infinity':
|
|
return 0;
|
|
default:
|
|
return Number(number);
|
|
}
|
|
},
|
|
formatNumber(number: NumberInput): string {
|
|
try {
|
|
return numeral(this.normalizeNumber(number)).format('0,0.[00]');
|
|
} catch (_e) {
|
|
return String(number);
|
|
}
|
|
},
|
|
formatPercentage(percentage: NumberInput): string {
|
|
try {
|
|
return numeral(this.normalizeNumber(percentage)).format('0.00%');
|
|
} catch (_e) {
|
|
return String(percentage);
|
|
}
|
|
},
|
|
formatBytes(number: NumberInput): string {
|
|
numeral.zeroFormat('0B');
|
|
|
|
let formattedNumber: string;
|
|
|
|
try {
|
|
formattedNumber = numeral(this.normalizeNumber(number)).format('0.0ib');
|
|
} catch (_e) {
|
|
formattedNumber = String(number);
|
|
}
|
|
|
|
numeral.zeroFormat(null);
|
|
|
|
return formattedNumber;
|
|
},
|
|
formatDecimalBytes(number: NumberInput): string {
|
|
numeral.zeroFormat('0B');
|
|
|
|
let formattedNumber: string;
|
|
|
|
try {
|
|
formattedNumber = numeral(this.normalizeNumber(number)).format('0.0b');
|
|
} catch (_e) {
|
|
formattedNumber = String(number);
|
|
}
|
|
|
|
numeral.zeroFormat(null);
|
|
|
|
return formattedNumber;
|
|
},
|
|
bytesToGb(bytes: number): number {
|
|
return parseFloat((bytes / this.BYTES_PER_GB).toFixed(2));
|
|
},
|
|
gbToBytes(gb: number): number {
|
|
return Math.round(gb * this.BYTES_PER_GB);
|
|
},
|
|
isNumber(possibleNumber: unknown): boolean {
|
|
return possibleNumber !== '' && !Number.isNaN(Number(possibleNumber));
|
|
},
|
|
};
|
|
|
|
export default NumberUtils;
|