diff options
Diffstat (limited to 'index.js')
| -rw-r--r-- | index.js | 101 |
1 files changed, 50 insertions, 51 deletions
@@ -17,79 +17,78 @@ basic.validate = function (s, b) { // 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 + if (b > 0) { + A = "-" + A } - var re = new RegExp ( "[^" + A + "]", "g" ) - return ! re.test(s) + 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 - ) + b = Math.abs(b) + return ( + ! isNaN(b) + && b > 1 + && b <= 36 + && (b % 1) === 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 - } + 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 + 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 + 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 + 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 Math.floor(n) } - return -1 * Math.floor(-n) + return -1 * Math.floor(-n) } |
