|
42 | 42 | /**
|
43 | 43 | * Generates an ObjectId
|
44 | 44 | */
|
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.'); |
59 | 59 | }
|
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 | + } |
61 | 77 |
|
62 | 78 | function checkValue(value) {
|
63 | 79 | if (/{{\s*([\w\W]+)\s*}}/g.test(value))
|
|
0 commit comments