diff options
| author | Jules Laplace <jules@okfoc.us> | 2017-03-08 12:24:47 +0100 |
|---|---|---|
| committer | Jules Laplace <jules@okfoc.us> | 2017-03-08 12:24:47 +0100 |
| commit | 0ccc76b28a573c4330e614403ede6ad40193d961 (patch) | |
| tree | 13827c57a3b8bfb033185d5daf941d94d99f77c6 /index.js | |
initial version of library
Diffstat (limited to 'index.js')
| -rw-r--r-- | index.js | 59 |
1 files changed, 59 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)) } + |
