-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.js
31 lines (28 loc) · 863 Bytes
/
format.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
function encodeAlphabet (value, alphabet, maxValue) {
const len = alphabet.length
let result = ''
while (value > 0) {
const rest = value % len
result = alphabet.charAt(rest) + result
value = Math.floor(value / len)
}
if (maxValue) {
const length = Math.ceil(Math.log(maxValue) / Math.log(len))
result = alphabet.charAt(0).repeat(length - result.length) + result
}
return result
}
exports.encode = encodeAlphabet
function decodeAlphabet (value, alphabet, throwIfUnrecognized) {
const len = alphabet.length
let exponent = 0
return value.split('').reverse().reduce((sum, e, i) => {
const index = alphabet.indexOf(e)
if (index === -1) {
if (throwIfUnrecognized) throw Error('unrecognized character')
return sum
}
return sum + index * len ** (exponent++)
}, 0)
}
exports.decode = decodeAlphabet