Last active
December 14, 2016 07:12
-
-
Save devsnek/39525ad76c1478e6affad50d8ebd99bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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