Created
September 26, 2018 09:05
-
-
Save williamcspace/5cc4300ed203af009aa748f7001e6207 to your computer and use it in GitHub Desktop.
Mongo's ObjectId generator
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
var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); | |
ObjectID.prototype.generate = function(time) { | |
if ('number' != typeof time) { | |
time = ~~(Date.now()/1000); | |
} | |
// Use pid | |
var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF; | |
var inc = this.get_inc(); | |
// Buffer used | |
var buffer = new Buffer(12); | |
// Encode time | |
buffer[3] = time & 0xff; | |
buffer[2] = (time >> 8) & 0xff; | |
buffer[1] = (time >> 16) & 0xff; | |
buffer[0] = (time >> 24) & 0xff; | |
// Encode machine | |
buffer[6] = MACHINE_ID & 0xff; | |
buffer[5] = (MACHINE_ID >> 8) & 0xff; | |
buffer[4] = (MACHINE_ID >> 16) & 0xff; | |
// Encode pid | |
buffer[8] = pid & 0xff; | |
buffer[7] = (pid >> 8) & 0xff; | |
// Encode index | |
buffer[11] = inc & 0xff; | |
buffer[10] = (inc >> 8) & 0xff; | |
buffer[9] = (inc >> 16) & 0xff; | |
// Return the buffer | |
return buffer; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment