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)) }