This repository was archived by the owner on Dec 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
74 lines (74 loc) · 2.28 KB
/
index.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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const basicTable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
* create index map
*
* @param table base62 string table
*/
function createIndexMap(table = basicTable) {
return table
.split('')
.reduce(function (result, value, index) {
result[value] = index;
return result;
}, {});
}
const basicIndexMap = createIndexMap();
/**
* decode to decimal number from base62 string
*
* @param str base62 string
* @param [baseTable=basicTable] base62 table
* @throws {TypeError} str is not a string
* @throws {Error} str is unexpected format
* @throws {Error} baseTable is not 62 in length
*/
function decode(str, baseTable = basicTable) {
if (typeof str !== 'string') {
throw new TypeError(`str must be a string: ${str}`);
}
if (!/^-?[\dA-Za-z]+$/.test(str)) {
throw new Error(`unexpected format: ${str}`);
}
if (baseTable.length !== 62) {
throw new Error('baseTable must be 62 in length');
}
const indexMap = baseTable === basicTable ? basicIndexMap : createIndexMap(baseTable);
const isNegative = str[0] === '-';
const numbers = (isNegative ? str.slice(1) : str).split('');
const numbersLength = numbers.length;
const result = numbers.reduce(function (result, n, index) {
return result + indexMap[n] * Math.pow(62, numbersLength - index - 1);
}, 0);
return isNegative ? -result : result;
}
exports.decode = decode;
/**
* encode to base62 string from number
*
* @param num integer
* @param [baseTable=basicTable] base62 table
* @throws {TypeError} num is not an Integer
* @throws {Error} baseTable is not 62 in length
*/
function encode(num, baseTable = basicTable) {
if (!Number.isSafeInteger(num)) {
throw new TypeError(`num is must be an integer: ${num}`);
}
if (baseTable.length !== 62) {
throw new Error('baseTable must be 62 in length');
}
if (num === 0) {
return '0';
}
const result = [];
let n = Math.abs(num);
while (n > 0) {
result.unshift(baseTable[n % 62]);
n = Math.floor(n / 62);
}
return num < 0 ? `-${result.join('')}` : result.join('');
}
exports.encode = encode;
//# sourceMappingURL=index.js.map