summaryrefslogtreecommitdiff
path: root/index.js
blob: 3a7697937a739da26caeb182ea1a0923b568c616 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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){
  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
  }
  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)
}