A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.
TypeScript amazon-primeelectronepic-games-launcherepic-games-storeepic-storegaminggoggog-galaxyheroic-games-launcherlinuxplay-gamesprotonsteamwine
const NON_BREAKING_SPACE = '\u00A0'
const UNKNOWN = '—'
export type DisplayUnits = 'mib' | 'mb'
export const MEBIBYTES = 'MiB'
export const MEBIBYTES_PER_SECOND = 'MiB/s'
export const MEGABYTES = 'MB'
const MEGABYTES_PER_SECOND = 'MB/s'
export const MEGABITS_PER_SECOND = 'Mbit/s'
const MIB_TO_MB = 1.048576
const toDisplayUnits = (value: number, units: DisplayUnits) =>
units === 'mb' ? value * MIB_TO_MB : value
export const mibPerSecondFromKbit = (kbitPerSecond: number) =>
kbitPerSecond / 8000 / MIB_TO_MB
export function formatMeasured(
value: number | null | undefined,
unit: string
): string {
if (value === null || value === undefined || !Number.isFinite(value)) {
return UNKNOWN
}
return `${Math.round(value * 10) / 10}${NON_BREAKING_SPACE}${unit}`
}
const BINARY_SIZE_UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB'] as const
const DECIMAL_SIZE_UNITS = ['B', 'kB', 'MB', 'GB', 'TB'] as const
export function formatSize(
bytes: number | null | undefined,
units: DisplayUnits
): string {
if (bytes === null || bytes === undefined || !Number.isFinite(bytes)) {
return UNKNOWN
}
if (bytes === 0) {
return formatMeasured(0, 'B')
}
const base = units === 'mb' ? 1000 : 1024
const symbols = units === 'mb' ? DECIMAL_SIZE_UNITS : BINARY_SIZE_UNITS
let exponent = Math.min(
Math.floor(Math.log(Math.abs(bytes)) / Math.log(base)),
symbols.length - 1
)
exponent = Math.max(exponent, 0)
let value = Math.round((bytes / base ** exponent) * 10) / 10
if (value >= base && exponent < symbols.length - 1) {
exponent += 1
value = Math.round((bytes / base ** exponent) * 10) / 10
}
return formatMeasured(value, symbols[exponent])
}
export function formatSpeed(
mebibytesPerSecond: number | null | undefined,
units: DisplayUnits
): string {
const value =
mebibytesPerSecond === null || mebibytesPerSecond === undefined
? mebibytesPerSecond
: toDisplayUnits(mebibytesPerSecond, units)
return formatMeasured(
value,
units === 'mb' ? MEGABYTES_PER_SECOND : MEBIBYTES_PER_SECOND
)
}