diff --git a/bases.js b/bases.js index fa64b17..7acc724 100644 --- a/bases.js +++ b/bases.js @@ -3,16 +3,19 @@ // See README.md for details. var bases = (typeof exports !== 'undefined' ? exports : (window.Bases = {})); +const Big = require('big.js'); // Returns a string representation of the given number for the given alphabet: bases.toAlphabet = function (num, alphabet) { var base = alphabet.length; var digits = []; // these will be in reverse order since arrays are stacks + num = Big(num); // execute at least once, even if num is 0, since we should return the '0': do { - digits.push(num % base); // TODO handle negatives properly? - num = Math.floor(num / base); + digits.push(num.mod(base)); // TODO handle negatives properly? + num = num.div(base); + num = new Big(num).round(0, 0); } while (num > 0); var chars = []; @@ -24,15 +27,15 @@ bases.toAlphabet = function (num, alphabet) { // Returns an integer representation of the given string for the given alphabet: bases.fromAlphabet = function (str, alphabet) { - var base = alphabet.length; + var base = new Big(alphabet.length); var pos = 0; - var num = 0; + var num = new Big(0); var c; while (str.length) { c = str[str.length - 1]; str = str.substr(0, str.length - 1); - num += Math.pow(base, pos) * alphabet.indexOf(c); + num = num.plus(base.pow(pos).times(alphabet.indexOf(c))); pos++; } diff --git a/package.json b/package.json index c029b48..141efad 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,28 @@ -{ "name": "bases" -, "version": "0.2.1" -, "description": "Utility for converting numbers to/from different bases/alphabets." -, "author": "Aseem Kishore " -, "homepage": "https://github.com/aseemk/bases.js" -, "keywords": ["alphabet", "base", "base-36", "base-58", "base-62"] -, "repository": - { "type": "git" - , "url": "https://github.com/aseemk/bases.js.git" - } -, "main": "bases.js" -, "dependencies": {} -, "engines": - { "node": "*" - } -, "scripts": - { "test": "node test" +{ + "name": "bases", + "version": "0.2.1", + "description": "Utility for converting numbers to/from different bases/alphabets.", + "author": "Aseem Kishore ", + "homepage": "https://github.com/aseemk/bases.js", + "keywords": [ + "alphabet", + "base", + "base-36", + "base-58", + "base-62" + ], + "repository": { + "type": "git", + "url": "https://github.com/aseemk/bases.js.git" + }, + "main": "bases.js", + "dependencies": { + "big.js": "^5.2.2" + }, + "engines": { + "node": "*" + }, + "scripts": { + "test": "node test" } } diff --git a/test.js b/test.js index 6e7b4f6..fd6a5d8 100644 --- a/test.js +++ b/test.js @@ -126,5 +126,13 @@ for (var base in DATA) { } } +const maxMd5Hash = 'ffffffffffffffffffffffffffffffff'; +const number = bases.fromBase(maxMd5Hash, 16); +const compacted = bases.toBase(number, 62); +console.log(compacted); +const backNumber = bases.fromBase(compacted, 62); +const backHash = bases.toBase(backNumber, 16); +assert.equal(backHash, maxMd5Hash); + // finally... console.log('All tests passed.');