Last active
November 17, 2015 22:49
-
-
Save carlosascari/5fca7ed47a44b79a37e0 to your computer and use it in GitHub Desktop.
Convert numbers into any base e.g: 2, 8,16, 64,1024, 65500, etc.
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
/** | |
* Provides BaseN class | |
* | |
* Encode and decode numbers as any base | |
* | |
* @example | |
* | |
* var baseX = new BaseN() // Default base is 65,535 | |
* var sample = 9007199254740991 | |
* var encoded = baseX.encode(sample) | |
* var decoded = baseX.decode(encoded) | |
* console.log(sample) | |
* console.log(encoded) | |
* console.log(decoded) | |
* | |
* @module BaseN | |
*/ | |
var BaseN = (function () { | |
/** | |
* @property DEFAULT_CHAR_MAP | |
* @type Array | |
*/ | |
var DEFAULT_CHAR_MAP = [] | |
for (var k = 0; k < 0xFFFF; k++) | |
{ | |
DEFAULT_CHAR_MAP[DEFAULT_CHAR_MAP.length] = String.fromCharCode(k) | |
} | |
/** | |
* @class BaseN | |
* @constructor | |
*/ | |
function BaseN(chars) | |
{ | |
if (typeof chars === 'number') | |
{ | |
if (chars > 1 && chars < 0x10000) | |
{ | |
var size = chars | |
chars = [] | |
for (var k = 0; k < size; k++) | |
{ | |
chars[chars.length] = String.fromCharCode(k) | |
} | |
} | |
else | |
{ | |
throw new Error('Base size must be between 2 and 65535') | |
} | |
} | |
if (typeof chars === 'string') | |
{ | |
chars = chars.split('') | |
} | |
if (Object.prototype.toString.call(chars) !== '[object Array]') | |
{ | |
chars = DEFAULT_CHAR_MAP | |
} | |
this.base = chars.length | |
this.chars = chars | |
this.map = {} | |
this.bits = 1 | |
while (this.base >> (this.bits + 1)) | |
{ | |
this.bits++; | |
} | |
for (var i = 0, len = chars.length; i < len; i++) | |
{ | |
this.map[ chars[i] ] = i | |
} | |
} | |
/** | |
* @method encode | |
* @param number {Number} | |
* @return String | |
*/ | |
BaseN.prototype.encode = function(number) | |
{ | |
if (!number) return this.chars[0] | |
var ret = '' | |
while (number > 0) | |
{ | |
var rem = number % this.base | |
number = Math.floor(number / this.base) | |
ret = this.chars[rem] + ret | |
} | |
return ret | |
} | |
/** | |
* @method decode | |
* @param encoded {String} | |
* @return Number | |
*/ | |
BaseN.prototype.decode = function(encoded) | |
{ | |
var decoded = 0, multi = 1; | |
for (var i = encoded.length - 1; i >= 0; i--) | |
{ | |
decoded += this.map[encoded.charAt(i)] * multi | |
multi = multi * this.base | |
} | |
return decoded | |
} | |
return BaseN | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment