Skip to content

Instantly share code, notes, and snippets.

@kchapelier
Last active December 2, 2015 22:26
Show Gist options
  • Save kchapelier/a992cc248d659cad0ccc to your computer and use it in GitHub Desktop.
Save kchapelier/a992cc248d659cad0ccc to your computer and use it in GitHub Desktop.
"use strict";
var multipliers = {
k: Math.pow(1024, 1),
m: Math.pow(1024, 2),
g: Math.pow(1024, 3),
t: Math.pow(1024, 4)
};
var regex = /([0-9]+[.,]?[0-9]*) *([kmgt]?)/ig;
/**
* Parse a size as a string,
* @param string
* @param unit
* @returns {int|null}
*/
var parseStringSize = function parseStringSize (string, unit) {
var result,
value;
if (result = regex.exec(string)) {
unit = unit ? unit[0] : result[2];
unit = unit.toLowerCase();
value = parseFloat(result[1].replace(',', '.'));
if (multipliers.hasOwnProperty(unit)) {
value = value * multipliers[unit];
}
return value;
}
return null;
};
module.exports = parseStringSize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment