Last active
December 2, 2015 22:26
-
-
Save kchapelier/a992cc248d659cad0ccc to your computer and use it in GitHub Desktop.
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
"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