-
Notifications
You must be signed in to change notification settings - Fork 3
/
b62.js
79 lines (61 loc) · 2.13 KB
/
b62.js
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
'use strict';
// dependencies
var Bignum = require('bignum');
var MAX_INT_PRECISION = Math.pow(2, 52); // http://www.w3schools.com/js/js_numbers.asp
exports = module.exports = B62;
var b62Operations = B62();
module.exports.encode = b62Operations.encode;
module.exports.decode = b62Operations.decode;
function B62(charset) {
var base62 = function () { };
base62.charset = charset || "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
base62.base = base62.charset.length;
base62.encode = function (input, encoding, opts) {
var self = base62;
if (!input) { return ''; }
if (typeof input === 'string' && opts && !encoding) {
input = new Bignum(input, opts);
} else if (typeof input === 'string') {
input = Bignum.fromBuffer(new Buffer(input, encoding), opts);
} else if (input instanceof Buffer) {
input = Bignum.fromBuffer(input, opts || encoding);
} else {
input = new Bignum(input, opts || encoding);
}
var binary = input,
dividend = new Bignum(binary),
result = '';
if (binary.eq(0)) { return '0'; }
while (binary.gt(MAX_INT_PRECISION)) {
binary = dividend.div(self.base);
result = self.charset[dividend.mod(self.base)] + result;
dividend = binary;
}
binary = binary.toNumber();
while (binary > 0) {
result = self.charset[binary % self.base] + result;
binary = Math.floor(binary / self.base);
}
return result;
};
base62.decode = function (str, encodingBase, opts) {
var self = base62;
var result = new Bignum(0),
chars = str.split('').reverse(),
multiplier = new Bignum(1),
idx = 0;
while (idx < chars.length /*&& multiplier < MAX_INT_PRECISION/self.base*/) {
multiplier = Bignum.pow(self.base, idx);
result = result.add(multiplier.mul(self.charset.indexOf(chars[idx])));
idx++;
}
if (opts !== undefined && !encodingBase) {
return result.toBuffer(opts);
} else if (typeof encodingBase === 'number') {
return result.toString(encodingBase);
} else {
return result.toBuffer(opts).toString(encodingBase);
}
};
return base62;
}