Skip to content

Instantly share code, notes, and snippets.

@devsnek
Last active December 14, 2016 07:12
Show Gist options
  • Save devsnek/39525ad76c1478e6affad50d8ebd99bd to your computer and use it in GitHub Desktop.
Save devsnek/39525ad76c1478e6affad50d8ebd99bd to your computer and use it in GitHub Desktop.
const leftpad = (v, n, c = '0') => String(v).length >= n ? '' + v : (String(c).repeat(n) + v).slice(-n);
class Snowflake {
constructor ({ epoch, workerId, datacenterId } = { 1288834974657, 1, process.pid }) {
this.epoch = epoch;
this.workerId = workerId;
this.dataCenterId = datacenterId;
this.incId = 0;
}
nextId() {
const timestamp = this.getTime().toString(2);
const worker = leftpad(this.workerId.toString(2), 5);
const datacenter = leftpad(this.dataCenterId.toString(2), 5);
const inc = leftpad(this.incId.toString(2), 12);
const snowflake = timestamp + worker + datacenter + inc;
this.incId++;
return parseInt(snowflake, 2);
}
getTime() {
return new Date().getTime() - this.epoch;
}
}
module.exports = Snowflake;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment