Last active
March 18, 2023 17:37
-
-
Save wirwolf/ec023ad8f6716c1ebbf9a5721bf3d621 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function findSuffix(quantity: string): string { | |
let ix = quantity.length - 1; | |
while (ix >= 0 && !/[\.0-9]/.test(quantity.charAt(ix))) { | |
ix--; | |
} | |
return ix === -1 ? '' : quantity.substring(ix + 1); | |
} | |
function quantityToScalar(quantity: string): number | bigint { | |
if (!quantity) { | |
return 0; | |
} | |
switch (suffix) { | |
case 'n': | |
return Number(quantity.substr(0, quantity.length - 1)).valueOf() / 1_000_000_000.0; | |
case 'u': | |
return Number(quantity.substr(0, quantity.length - 1)).valueOf() / 1_000_000.0; | |
case 'm': | |
return Number(quantity.substr(0, quantity.length - 1)).valueOf() / 1000.0; | |
case 'k': | |
return BigInt(quantity.substr(0, quantity.length - 1)) * BigInt(1000); | |
case 'M': | |
return BigInt(quantity.substr(0, quantity.length - 1)) * BigInt(1000 * 1000); | |
case 'G': | |
return BigInt(quantity.substr(0, quantity.length - 1)) * BigInt(1000 * 1000 * 1000); | |
case 'T': | |
return ( | |
BigInt(quantity.substr(0, quantity.length - 1)) * BigInt(1000 * 1000 * 1000) * BigInt(1000) | |
); | |
case 'P': | |
return ( | |
BigInt(quantity.substr(0, quantity.length - 1)) * | |
BigInt(1000 * 1000 * 1000) * | |
BigInt(1000 * 1000) | |
); | |
case 'E': | |
return ( | |
BigInt(quantity.substr(0, quantity.length - 1)) * | |
BigInt(1000 * 1000 * 1000) * | |
BigInt(1000 * 1000 * 1000) | |
); | |
case 'Ki': | |
return BigInt(quantity.substr(0, quantity.length - 2)) * BigInt(1024); | |
case 'Mi': | |
return BigInt(quantity.substr(0, quantity.length - 2)) * BigInt(1024 * 1024); | |
case 'Gi': | |
return BigInt(quantity.substr(0, quantity.length - 2)) * BigInt(1024 * 1024 * 1024); | |
case 'Ti': | |
return ( | |
BigInt(quantity.substr(0, quantity.length - 2)) * BigInt(1024 * 1024 * 1024) * BigInt(1024) | |
); | |
case 'Pi': | |
return ( | |
BigInt(quantity.substr(0, quantity.length - 2)) * | |
BigInt(1024 * 1024 * 1024) * | |
BigInt(1024 * 1024) | |
); | |
case 'Ei': | |
return ( | |
BigInt(quantity.substr(0, quantity.length - 2)) * | |
BigInt(1024 * 1024 * 1024) * | |
BigInt(1024 * 1024 * 1024) | |
); | |
default: | |
throw new Error(`Unknown suffix: ${suffix}`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment