Closed gustavotoyota closed 1 year ago
I decided to write my own converter:
const alphabet =
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
const charMap = new Map<string, number>();
for (let i = 0; i < alphabet.length; i++) {
charMap.set(alphabet[i], i);
}
export function nanoidToBytes(input: string): Uint8Array {
const bytes = new Uint8Array(16);
let bitPos = 0;
let bytePos = 0;
let oldBitOffset = 0;
for (let i = 0; i < 21; i++) {
bytes[bytePos] |= charMap.get(input[i])! << oldBitOffset;
bitPos += 6;
bytePos = bitPos >>> 3;
const newBitOffset = bitPos % 8;
if (oldBitOffset > newBitOffset) {
bytes[bytePos] |= charMap.get(input[i])! >>> (8 - oldBitOffset);
}
oldBitOffset = newBitOffset;
}
return bytes;
}
Also a bit surprised that there isn't any function included to convert a nanoid into it's binary representation.
Couldn't find any info on this.