ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.33k stars 788 forks source link

How to convert nanoid into Uint8Array? #404

Closed gustavotoyota closed 1 year ago

gustavotoyota commented 1 year ago

Couldn't find any info on this.

gustavotoyota commented 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;
}
magJ commented 1 year ago

Also a bit surprised that there isn't any function included to convert a nanoid into it's binary representation.