Skip to content

Instantly share code, notes, and snippets.

@odra
Last active March 18, 2016 14:42
Show Gist options
  • Save odra/1f5aa8ee9f1776e2e9bc to your computer and use it in GitHub Desktop.
Save odra/1f5aa8ee9f1776e2e9bc to your computer and use it in GitHub Desktop.
objectid
function ObjectId () {
this.str = this.genID();
}
ObjectId.prototype.genID = function () {
var float32 = 16777216;
var int16 = 65536;
var ts = Math.floor(Date.now() / 1000).toString(16);
var mid = Math.floor(Math.random() * (int16)).toString(16);
var pid = Math.floor(Math.random() * (float32)).toString(16);
var counter = Math.floor(Math.random() * (float32)).toString(16);
return '00000000'.substr(0, 8 - ts.length) + ts +
'000000'.substr(0, 6 - mid.length) + mid +
'0000'.substr(0, 4 - pid.length) + pid +
'000000'.substr(0, 6 - counter.length) + counter;
};
ObjectId.prototype.getTimestamp = function () {
return new Date(parseInt(this.valueOf().slice(0, 8), 16) * 1000);
};
ObjectId.prototype.toString = function () {
return 'ObjectId("' + this.str + '")';
};
ObjectId.prototype.valueOf = function () {
return this.str;
};
//usage
var o = new ObjectId();
console.log(o.getTimestamp());
console.log(o.toString());
console.log(o.valueOf());
console.log(o.str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment