From 26f3fd1352a7fb73b7e8317a45f2a38975467429 Mon Sep 17 00:00:00 2001 From: Jules Laplace Date: Wed, 8 Mar 2017 15:46:03 +0100 Subject: test all functions and fix bugs --- index.js | 56 ++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 18 deletions(-) (limited to 'index.js') diff --git a/index.js b/index.js index 6218073..71d93d9 100644 --- a/index.js +++ b/index.js @@ -6,32 +6,41 @@ 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)) + 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, b) - var re = new RegExp ( "[^" + A + "]" ) - return !! re.match(s) + 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 (b !== 0 && b !== 1 && b !== -1 && (Math.abs(b) % 2) === 0) + 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)) { + 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) + n += basic.abedecary.indexOf(s[len-1-i]) * Math.pow(b, i) } return n } @@ -42,23 +51,34 @@ 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 = "" - var dividend, residual while (n) { - remainder = basic.mod(n, b) - n = Math.floor(n/b) - if (remainder) { + var remainder = n % b + n = basic.floor(n / b) + if (remainder < 0) { n += 1 + remainder -= b } - s += basic.abedecary[n] + s = basic.abedecary[remainder] + s + } + if (is_negative && b > 0) { + s = "-" + s } return s } -// Compute the residual of N mod M -// Handle negative N and M correctly -basic.mod = function (n,m){ - m = Math.abs(m) - return n-(m * Math.floor(n/m)) +// 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) } -- cgit v1.2.3-70-g09d2