Skip to content

Instantly share code, notes, and snippets.

@Rene-Roscher
Created February 19, 2024 01:12
Show Gist options
  • Select an option

  • Save Rene-Roscher/695ca298f910cfc658366aeb62d3cc4c to your computer and use it in GitHub Desktop.

Select an option

Save Rene-Roscher/695ca298f910cfc658366aeb62d3cc4c to your computer and use it in GitHub Desktop.
Snowflake IDs in Javascript (For 53bit)
// 53 bits unique id: 41 bits for time in milliseconds + 12 bits for sequence number
class Snowflake {
constructor(options) {
options = options || {};
this.seq = 0;
this.offset = options.offset || 0; // 2019-04-01T00:00:00Z
this.lastTime = 0;
}
generate() {
const time = Date.now(),
bTime = (time - this.offset).toString(2).padStart(41, '0'); // 41 Bits
// get the sequence number
if (this.lastTime == time) {
this.seq++;
if (this.seq > 4095) {
this.seq = 0;
// make system wait till time is been shifted by one millisecond
while (Date.now() <= time) {}
}
} else {
this.seq = 0;
}
this.lastTime = time;
let bSeq = this.seq.toString(2).padStart(12, '0'); // 12 Bits
const bid = bTime + bSeq;
let id = "";
id = BigInt('0b' + bid).toString();
return id;
}
}
module.exports = new Snowflake({
offset: new Date('2019-04-01T00:00:00Z').getTime()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment