Skip to content

Instantly share code, notes, and snippets.

@zhisme
Last active April 16, 2018 19:58
Show Gist options
  • Save zhisme/15cdec8a997a3eec54ceb1004fb09c3c to your computer and use it in GitHub Desktop.
Save zhisme/15cdec8a997a3eec54ceb1004fb09c3c to your computer and use it in GitHub Desktop.
Implementation of Ruby on Rails ActiveSupport::NumberHelper::NumberToHumanSizeConverter in javascript < ES5
var NumberToHumanSizeConverter = {
STORAGE_UNITS: ['bytes', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb'],
base: 1024,
parsedNum: null,
defaults: {
delimeter: '.',
precision: '2'
},
convert: function(number) {
this.parsedNum = parseFloat(number);
if (this._isSmallerThanBase(this.parsedNum)) {
var numberToFormat = parseInt(this.parsedNum);
} else {
var numberToFormat = this.parsedNum / (this.base ** this._exponent());
}
var humanSize = this._conversionFormat(numberToFormat);
return interpolate("%s %s", [humanSize, this._unit().toUpperCase()])
},
_isSmallerThanBase: function() {
if(parseInt(this.parsedNum) < this.base) return true;
return false;
},
_exponent: function() {
var max = this.STORAGE_UNITS.size - 1;
var exp = parseInt(Math.log(this.parsedNum) / Math.log(this.base));
if(exp > max) {
return exp;
}
return exp;
},
_unit: function() {
return this._isSmallerThanBase() ? "byte" : this.STORAGE_UNITS[this._exponent()]
},
_conversionFormat: function(converted) {
var formatted = converted;
if (!this._isInt(converted)) {
formatted = formatted.toFixed(this.defaults.precision).
toString().
replace('.', this.defaults.delimeter);
}
return formatted;
},
_isInt: function(n) {
return parseInt(n) === n;
}
};
// See this for original answer https://stackoverflow.com/a/31007976/5347939
var interpolate = function(theString, argumentArray) {
var regex = /%s/;
var _r = function(p,c) { return p.replace(regex, c); }
return argumentArray.reduce(_r, theString);
};
@zhisme
Copy link
Author

zhisme commented Feb 22, 2018

Usage

NumberToHumanSizeConverter.convert(1024 * 1000000);
=> "976.56 MB"

NumberToHumanSizeConverter.convert(1024);
=> "1 KB"

NumberToHumanSizeConverter.convert(764);
=> "764 BYTES"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment