sutra
2018-05-29 00:10:35 +08:00
曾经拿 Javascript 写了一段让它表现得更短的代码,思路也就是 #1 的用更多的字符来编码:
通常我们用 0-F 16 个字符来编码,我这里改成了用 62 个字符来编码:
(不过由于 Javascript 浮点数最大能表达的数字的问题,我这段代码并不是最佳的)
// var DIGITS = "0123456789ABCDEF"
// var DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$&'()*+/:;=?@._~"
var DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var BASE = DIGITS.length
var SEPARATOR = '-'
function encodeNumber(num) {
var digit
var residual = Math.floor(num)
var result = ''
do {
digit = residual % BASE
result = DIGITS.charAt(digit) + result
residual = Math.floor(residual / BASE)
} while (residual > 0)
return result
}
function decodeNumber(str) {
var result = 0
var digits = str.split('')
var e, l = digits.length
for (e = 0; e < l; e++) {
result = (result * BASE) + DIGITS.indexOf(digits[e])
}
return result
}
function encodeUUID(uuid) {
var results = []
var s = uuid.replace(/-/g, '').toUpperCase()
var uuidInts = [
parseInt(s.substring(0, 8), 16),
parseInt(s.substring(8, 16), 16),
parseInt(s.substring(16, 24), 16),
parseInt(s.substring(24, 32), 16)
]
var i, l = uuidInts.length
for (i = 0; i < l; i++) {
results.push(encodeNumber(uuidInts[i]))
}
return results.join(SEPARATOR)
}
function decodeUUID(str) {
var uuidStrs = str.split(SEPARATOR)
var i, l = uuidStrs.length
var result = ''
var pad = '00000000'
var s
for (i = 0; i < l; i++) {
s = decodeNumber(uuidStrs[i]).toString(16)
s = pad.substring(0, pad.length - s.length) + s
result += s
}
return result.replace(/([A-Za-z0-9]{8})([A-Za-z0-9]{4})([A-Za-z0-9]{4})([A-Za-z0-9]{4})([A-Za-z0-9]{12})/, "$1-$2-$3-$4-$5").toUpperCase()
}
module.exports = {
encodeUUID: encodeUUID,
decodeUUID: decodeUUID
}