Last active
November 25, 2019 15:33
-
-
Save sbstp/f41d40daa5823596346620c27e293f74 to your computer and use it in GitHub Desktop.
Parse kubernetes memory units
This file contains 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 parseMemory(units) { | |
function multiply(amount, scale, base) { | |
switch (scale.toLowerCase()) { | |
case 'k': return amount * Math.pow(base, 1); | |
case 'm': return amount * Math.pow(base, 2); | |
case 'g': return amount * Math.pow(base, 3); | |
case 't': return amount * Math.pow(base, 4); | |
case 'p': return amount * Math.pow(base, 5); | |
case 'e': return amount * Math.pow(base, 6); | |
default: throw new ValueError("Unknown unit: " + scale); | |
} | |
} | |
if (typeof units !== "string") { | |
throw new TypeError("expected string"); | |
} | |
units = units.trim(); | |
// Try to parse SI units | |
var m = units.match(/^(\d+)\s*([KMGPE])i$/) | |
if (m != null) { | |
return multiply(parseInt(m[1]), m[2], 1024); | |
} | |
// Try to parse thousands | |
var m = units.match(/^(\d+)\s*([KMGPE])$/) | |
if (m != null) { | |
return multiply(parseInt(m[1]), m[2], 1000); | |
} | |
throw ValueError("Unknown units: " + units); | |
} | |
console.log(parseMemory("28 Mi")) | |
console.log(parseMemory("28M")) | |
console.log(parseMemory("5Pi")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment