diff options
| -rw-r--r-- | index.js | 59 | ||||
| -rw-r--r-- | package.json | 19 |
2 files changed, 78 insertions, 0 deletions
diff --git a/index.js b/index.js new file mode 100644 index 0000000..f168d16 --- /dev/null +++ b/index.js @@ -0,0 +1,59 @@ + +module.exports = basic = {} + +// Handle bases up to base 36 +basic.abedecary = "0123456789abcdefghijklmnopqrstuvwxyz" + +// Validate that a string s represents a number in base b +basic.validate = function (s, b) { + return (base.validate_base(b) && base.validate_digits(s, b)) +} + +// Validate that a string does not contain numerals +// foreign to a particular base. +basic.validate_digits = function(s, b) { + var A = basic.abedecary.substr(0, b) + var re = new RegExp ( "[^" + A + "]" ) + return !! re.match(s) +} + +// Validate that a base is valid. +basic.validate_base = function(b){ + return (b === 0 || b === 1 || b === -1 && (Math.abs(b) % 2) === 0) +} + +// Convert a string s representing a number in base b +// to an integer. Assumes s is big-endian. +basic.toNumber = function (s, b) { + if (! basic.validate(s,b)) { + return NaN + } + var n = 0 + s = s.reverse() + for (var i = 0, len = s.length; i < len; i++) { + n += parseInt(s[i]) * Math.pow(b, i) + } + return n +} + +// Convert an integer n to a string representing that +// integer in base b, big-endian. +basic.toString = function (n, b) { + if (! basic.validate_base(b)) { + throw new Error ("invalid base") + } + var s = "" + var dividend, residual + while (n) { + remainder = mod(n, b) + n = Math.floor(n/b) + if (remainder) { + n += 1 + } + s += basic.abedecary[n] + } + return s +} + +function mod(n,m){ return n-(m * Math.floor(n/m)) } + diff --git a/package.json b/package.json new file mode 100644 index 0000000..d322799 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "basic", + "version": "1.0.0", + "description": "convert between bases", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/julescarbon/basic.git" + }, + "author": "julie", + "license": "UNLICENSED", + "bugs": { + "url": "https://github.com/julescarbon/basic/issues" + }, + "homepage": "https://github.com/julescarbon/basic#readme" +} |
