-
-
Save solenoid/1372386 to your computer and use it in GitHub Desktop.
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(); | |
}; |
Thank You, just what am looking for
I wrote one for Lua -
function mongoObjectId()
return string.format("%x", os.time())..string.gsub('xxxxxxxxxxxxxxxx', 'x', function (c)
return string.format('%x', math.random(0, 15))
end)
end
OMG thank you so much
👌
And TypeScript - returning the whole oid structure
generateId(): {} {
const timestamp = (new Date().getTime() / 1000 | 0).toString(16);
const oid = timestamp + 'xxxxxxxxxxxxxxxx'
.replace(/[x]/g, _ => (Math.random() * 16 | 0).toString(16))
.toLowerCase();
return { "$oid": oid };
}
The code has a bug, because if random resulted 1 then (Math.random() * 16 | 0).toString(16) will result "10" which is two characters, leading to invalid ObjectId that is supposed to be 24 characters long.
This random string generate function is +50% faster than the method used in the function above (measured by jsben.ch).
function getRandomString(length) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var randS = "";
while(length > 0) {
randS += chars.charAt(Math.floor(Math.random() * chars.length));
length--;
}
return randS;
}
Ps: generated string will contain uppercase characters, remove upper characters in var chars
if you don't want them
Thanks! ;)
Cool thank you! :) 👍
Thank you so much.
👍 Good job
Thanks!
The code has a bug, because if random resulted 1 then (Math.random() * 16 | 0).toString(16) will result "10" which is two characters, leading to invalid ObjectId that is supposed to be 24 characters long.
Math.random()
returns [0, 1), inclusive of 0, but not 1.
this code from bson may more useful
https://github.com/mongodb/js-bson/blob/dc9c1bb284a6c08e07f14e700bdbfb0fd57e5a13/lib/objectid.js#L154
Based on the above comments I did a sh alias
alias objectidgen='node -e "console.log((function objectidgen(length = 16) {var timestamp = (new Date().getTime() / 1000 | 0).toString(16);return timestamp + \"xxxxxxxxxxxxxxxx\".replace(/[x]/g, _ => (Math.random() * 16 | 0).toString(16)).toLowerCase();})())"'
For macOS users:
alias objectidgen='node -e "console.log((function objectidgen(length = 16) {var timestamp = (new Date().getTime() / 1000 | 0).toString(16);return timestamp + \"xxxxxxxxxxxxxxxx\".replace(/[x]/g, _ => (Math.random() * 16 | 0).toString(16)).toLowerCase();})())" | pbcopy'
Thanks! This code useful for me!
Thank you so much man!!!
Thank you so much man!!!
I appreciate that you shared this. It is a simple, logical function and integrates nicely with my Express backend.
@solenoid what about the collision of this random id generation method?
Perfect, thanks!!
simple and quick solution. thanks
here is the function in coffee script:
mongoObjectId: () ->
timestamp = ((new Date).getTime() / 1000 | 0).toString(16)
timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, ->
(Math.random() * 16 | 0).toString 16
).toLowerCase()
It saved my life. lol
Thanks dude!
Thanks!
Thanks a lot, it was very useful!
I made a Golang version for a project
func mongoObjectId() string {
ts := time.Now().UnixMilli() / 1000
id := strconv.FormatInt(ts, 16)
for i := 0; i < 16; i++ {
id += fmt.Sprintf("%x", rand.Intn(16))
}
return id
}
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())
.
Thank you for this! I implemented this in C# with Unity, here's my version which returns a string:
private string GenerateID ()
{
Int64 val = 0;
var st = new DateTime(1970,1,1);
TimeSpan t = (DateTime.Now.ToUniversalTime () - st);
val = (Int64) (t.TotalMilliseconds+0.5);
char[] startVal = val.ToString ("X").ToCharArray ();
string timestamp = "";
for (int i = 0; i < 10; i++)
{
timestamp += startVal[i];
}
int num = 0;
for (int i = 0; i < 14; i++)
{
num = UnityEngine.Random.Range (1,16);
timestamp += num.ToString ("X");
}
return timestamp.ToLower ();
}
Maybe someone will find it useful :)