Skip to content

Commit

Permalink
⚡️ Faster unmap for ulid (#4091)
Browse files Browse the repository at this point in the history
* ⚡️ Faster unmap for `ulid`

* versions
  • Loading branch information
dubzzz committed Jul 19, 2023
1 parent 096685c commit efc49d4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
8 changes: 8 additions & 0 deletions .yarn/versions/04697a61.yml
@@ -0,0 +1,8 @@
releases:
fast-check: minor

declined:
- "@fast-check/ava"
- "@fast-check/jest"
- "@fast-check/vitest"
- "@fast-check/worker"
Expand Up @@ -27,7 +27,6 @@ const encodeSymbolLookupTable: Record<number, string> = {
/** @internal */
const decodeSymbolLookupTable: Record<string, number> = {
'0': 0,
O: 0,
'1': 1,
'2': 2,
'3': 3,
Expand Down Expand Up @@ -106,21 +105,22 @@ export function paddedUintToBase32StringMapper(paddingLength: number) {
};
}

/** @internal */
const Base32Regex = /^[0-9A-HJKMNP-TV-Z]+$/;

/** @internal */
export function uintToBase32StringUnmapper(value: unknown): number {
if (typeof value !== 'string') {
throw new Error('Unsupported type');
}

const normalizedBase32str = value.toUpperCase();
if (!Base32Regex.test(normalizedBase32str)) {
throw new Error('Unsupported type');
let accumulated = 0;
let power = 1;
for (let index = value.length - 1; index >= 0; --index) {
const char = value[index].toUpperCase();
const numericForChar = decodeSymbolLookupTable[char];
if (numericForChar === undefined) {
throw new Error('Unsupported type');
}
accumulated += numericForChar * power;
power *= 32;
}

const symbols = normalizedBase32str.split('').map((char) => decodeSymbolLookupTable[char]);

return symbols.reduce((prev, curr, i) => prev + curr * Math.pow(32, symbols.length - 1 - i), 0);
return accumulated;
}

0 comments on commit efc49d4

Please sign in to comment.