Created
November 17, 2011 04:49
-
-
Save solenoid/1372386 to your computer and use it in GitHub Desktop.
javascript 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 mongoObjectId = function () { | |
var timestamp = (new Date().getTime() / 1000 | 0).toString(16); | |
return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() { | |
return (Math.random() * 16 | 0).toString(16); | |
}).toLowerCase(); | |
}; |
Impl in rust:
use chrono::Utc;
use rand::Rng;
use std::fmt;
fn mongo_object_id() -> String {
let ts = Utc::now().timestamp_millis() / 1000;
let mut id = format!("{:x}", ts);
for _ in 0..16 {
let random_digit = rand::thread_rng().gen_range(0..16);
id.push_str(&format!("{:x}", random_digit));
}
id
}
fn main() {
let object_id = mongo_object_id();
println!("{}", object_id);
}
// [dependencies]
// chrono = "0.4"
// rand = "0.8"
A simple python implementation
import time
import random
def mongo_object_id():
timestamp = hex(int(time.time()))[2:]
rest = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
return (timestamp + rest).lower()
I use console.log(new (require('bson').ObjectId)().toString())
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot, it was very useful!
I made a Golang version for a project