cluster-id
Version:
Database cluster friendly object id with great query isolation.
52 lines (45 loc) • 1.43 kB
JavaScript
var BASE = 64
var SYMBOL_BITS = 6
/**
* base64 in ASCII char code ascending order for correct records ordering in
* the databases that use lexicographic ordering (LevelDB, RocksDB, CockroachDB).
* This important feature allows to keep sorting by id identical to sorting by
* record creation date encoded in id.
* Note: standard base64 don't put symbols in lexicographic ordering.
*/
var ALPHABET = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
// separator between time and other parts of id
var ZERO = encode(0)
function encode(num, minLength) {
// console.log('encode', num)
var buf = []
do {
buf.push(ALPHABET[num % BASE])
num = Math.floor(num / BASE)
// console.log('num', num)
} while (num > 0)
// console.log('str', str)
var encoded = buf.reverse().join("")
if (minLength && encoded.length < minLength) {
encoded = encoded.padStart(minLength, ZERO)
}
return encoded
}
function decode(base64Str) {
var num = 0
for (var lastI = base64Str.length - 1, i = lastI; i >= 0; i--) {
var symbol = base64Str.charAt(i)
var digit = ALPHABET.indexOf(symbol)
num += digit * Math.pow( BASE, (lastI - i) )
}
return num
}
// maximal number for given symbol count
var maxNum = function (symbols) { return Math.pow( BASE, symbols ) - 1; }
module.exports = {
encode: encode,
decode: decode,
maxNum: maxNum,
BASE: BASE,
SYMBOL_BITS: SYMBOL_BITS,
}