Skip to content

Commit 9cd7b81

Browse files
committed
feat: ObjectId() returns an object containg the parts iof the _id along with a toString() function
1 parent bd4c150 commit 9cd7b81

File tree

1 file changed

+31
-15
lines changed

1 file changed

+31
-15
lines changed

src/index.js

+31-15
Original file line numberDiff line numberDiff line change
@@ -42,22 +42,38 @@
4242
/**
4343
* Generates an ObjectId
4444
*/
45-
const ObjectId = (id) => {
46-
// Define the rnd function
47-
const rnd = (r16) => Math.floor(r16).toString(16);
48-
49-
if (id === undefined) {
50-
// If id is undefined, generate a new ObjectId
51-
return rnd(Date.now() / 1000) + '0'.repeat(16).replace(/./g, () => rnd(Math.random() * 16));
52-
} else {
53-
// Check if the provided id is a valid ObjectId
54-
const validIdRegex = /^[0-9a-fA-F]{24}$/;
55-
if (!validIdRegex.test(id)) {
56-
throw new Error('Invalid ObjectId');
57-
}
58-
return id; // Return the valid ObjectId as a string
45+
let counter = 0;
46+
function ObjectId(inputId) {
47+
if (inputId && /^[0-9a-fA-F]{24}$/.test(inputId)) {
48+
// If a valid ObjectId is provided, return it as a custom ObjectId object
49+
return {
50+
timestamp: inputId.substring(0, 8),
51+
processId: inputId.substring(8, 20),
52+
counter: inputId.substring(20),
53+
toString: function () {
54+
return this.timestamp + this.processId + this.counter;
55+
}
56+
};
57+
} else if (inputId) {
58+
throw new Error('Invalid ObjectId provided.');
5959
}
60-
};
60+
61+
// Generate a new custom ObjectId
62+
const timestampHex = Math.floor(Date.now() / 1000).toString(16).padStart(8, '0');
63+
const processIdHex = Math.floor(Math.random() * 0x100000000000).toString(16).padStart(12, '0');
64+
counter = (counter + 1) % 10000;
65+
const counterHex = counter.toString(16).padStart(4, '0');
66+
67+
// Return the custom ObjectId object with a toString() method
68+
return {
69+
timestamp: timestampHex,
70+
processId: processIdHex,
71+
counter: counterHex,
72+
toString: function () {
73+
return this.timestamp + this.processId + this.counter;
74+
}
75+
};
76+
}
6177

6278
function checkValue(value) {
6379
if (/{{\s*([\w\W]+)\s*}}/g.test(value))

0 commit comments

Comments
 (0)