var basic = {} if (! ('window' in this)) { 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 (basic.validate_base(b) && basic.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, Math.abs(b)) if (b > 0) { A = "-" + A } var re = new RegExp ( "[^" + A + "]", "g" ) return ! re.test(s) } // Validate that a base is valid. basic.validate_base = function(b){ return ( ! isNaN(b) && b !== 0 && b !== 1 && b !== -1 && (Math.abs(b) % 1) === 0 && Math.abs(b) <= 36 ) } // 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, is_negative = false if (s.indexOf("-") == 0) { is_negative = true s = s.substr(1) } for (var i = 0, len = s.length; i < len; i++) { n += basic.abedecary.indexOf(s[len-1-i]) * Math.pow(b, i) } if (is_negative) { n *= -1 } 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") } if (n === 0) { return "0" } var is_negative = n < 0 if (is_negative && b > 0) { n = Math.abs(n) } var s = "" while (n) { var remainder = n % b n = basic.floor(n / b) if (remainder < 0) { n += 1 remainder -= b } s = basic.abedecary[remainder] + s } if (is_negative && b > 0) { s = "-" + s } return s } // Remove the mantissa from a number, handling negative numbers basic.floor = function (n){ if (n >= 0) { return Math.floor(n) } return -1 * Math.floor(-n) }