Last active
April 16, 2018 19:58
-
-
Save zhisme/15cdec8a997a3eec54ceb1004fb09c3c to your computer and use it in GitHub Desktop.
Implementation of Ruby on Rails ActiveSupport::NumberHelper::NumberToHumanSizeConverter in javascript < ES5
This file contains hidden or 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
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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage