summaryrefslogtreecommitdiff
path: root/index.js
blob: 6218073f023428bdb08d208adac47fdd3261a952 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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 = basic.mod(n, b)
    n = Math.floor(n/b)
		if (remainder) {
		  n += 1
		}
		s += basic.abedecary[n]
	}
	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))
}