Skip to content

Instantly share code, notes, and snippets.

@sbstp
Last active November 25, 2019 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbstp/f41d40daa5823596346620c27e293f74 to your computer and use it in GitHub Desktop.
Save sbstp/f41d40daa5823596346620c27e293f74 to your computer and use it in GitHub Desktop.
Parse kubernetes memory units
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