Snowflake Numeric ID Generator
Generate 64-bit Snowflake IDs with timestamp worker ID and sequence for sortable numeric unique IDs without coordination.
Code
export function snowflake(workerId=0,{epoch=1700000000000,workerBits=10,seqBits=12}={}){const maxW=(1<<workerBits)-1,maxS=(1<<seqBits)-1;if(workerId<0||workerId>maxW)throw new Error('workerId out of range');let lastTs=-1,seq=0;function next(){let ts=Date.now()-epoch;if(ts<lastTs)throw new Error('clock moved backwards');if(ts===lastTs){seq=(seq+1)&maxS;if(seq===0){while(ts<=lastTs)ts=Date.now()-epoch;}}else seq=0;lastTs=ts;return(ts<<(workerBits+seqBits))|(workerId<<seqBits)|seq;}return{next};}Report a problem with this exampleOpens a pre-filled issue on GitHub.