Skip to content

Instantly share code, notes, and snippets.

@osartun
Last active December 11, 2015 09:29
Show Gist options
  • Save osartun/4580478 to your computer and use it in GitHub Desktop.
Save osartun/4580478 to your computer and use it in GitHub Desktop.
In case you've always wanted to create your own Numbering System, here you go.
// Your own numbering system
function NumberingSystem(digits) {
this.setSystem(digits);
}
NumberingSystem.prototype = {
setSystem: function (digits) {
this.digits = typeof digits === "string" ? digits : "0123456789";
this.base = this.digits.length;
},
toDecimal: function (nr) {
if (!nr.split) return NaN;
var nrDigits = nr.split(""), digit, res = 0, conversion, isValid = true;
while (isValid && (digit = nrDigits.shift()) != undefined) {
res *= this.base;
res += (conversion = this.digits.indexOf(digit)) === -1 ? (isValid = false) : conversion;
}
return isValid ? res : NaN;
},
fromDecimal: function (nr) {
var division, integer = parseInt(nr), remainder, res = [];
if (integer === 0) {
return this.digits[0];
}
while (integer) {
division = integer/this.base;
integer = parseInt(division);
remainder = division%1;
res.unshift(this.digits[Math.round(remainder*this.base)]); // Sometimes it's 4.99999 instead of 5 or the like. That's why we need to Math.round the number
}
return res.join("");
},
to: function (nr, nrSystem) {
if (!nrSystem instanceof NumberingSystem) return NaN;
return nrSystem.fromDecimal(this.toDecimal(nr));
},
from: function (nr, nrSystem) {
if (!nrSystem instanceof NumberingSystem) return NaN;
return this.fromDecimal(nrSystem.toDecimal(nr));
}
};
/**
* Usage:
*
* var myNumberingSystem = new NumberingSystem("What the fuck! A numbering System?! Why that?");
*
* myNumberingSystem.fromDecimal(7533554402803);
*
* "because!"
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment