Skip to content

Instantly share code, notes, and snippets.

@great-elephant
Created June 9, 2024 07:43
Show Gist options
  • Select an option

  • Save great-elephant/44f3aec6cd5f00015bb6a4ab18e33353 to your computer and use it in GitHub Desktop.

Select an option

Save great-elephant/44f3aec6cd5f00015bb6a4ab18e33353 to your computer and use it in GitHub Desktop.
ID Generator
/**
* Refs:
* - https://gist.github.com/CatsMiaow/b479e96d5613dbd4711ab6d768b3eea0
* - https://stackoverflow.com/a/61852309
*/
class BigIntBase62 {
private static CHARSET =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
static encode(integer: bigint | number): string {
let num = BigInt(integer);
let rs: string = '';
while (num > 0) {
rs = this.CHARSET.charAt(Number(num % 62n)) + rs;
num = num / 62n;
}
return rs || '0';
}
}
/**
* Refs:
* - https://github.com/theinternetfolks/snowflake
* - https://www.w3schools.com/js/js_bitwise.asp
*/
class Snowflake {
private static COUNT = 0;
static gen(ts = Date.now(), shardId = 1) {
if (shardId >= 1024)
throw new Error(
'Current snowflake ID implementation only support shard id < 1024',
);
return (
(BigInt(ts) << 22n) |
(BigInt(shardId) << 12n) |
BigInt(this.COUNT++ % 4096)
);
}
}
/**
* Universal ID generator(shortened version).
*
* __How it works:__
* This ID generator use Snowflake ID shortened by base62.
*/
export const genUid = () => BigIntBase62.encode(Snowflake.gen());
/**
* Time based ID generator.
*
* __How it works:__
* This ID generator use current milliseconds timestamp(divided by 100)
* and shortened by base62.
*
* __Note:__
* This ID generator can only create 10 IDs/second, so it is only suitable
* for data such as a user's avatar version(eg: ATPulcGQ2SE.jpg?v=7vzmchq).
*/
export function genTimeId(): string {
return BigIntBase62.encode(Math.floor(Date.now() / 100));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment