add objectid util functions

This commit is contained in:
poros 2025-01-21 17:55:05 +01:00
parent 64082d4e6d
commit 7e5e4d00ee
3 changed files with 28 additions and 5 deletions

24
src/utils/objectId.ts Normal file
View file

@ -0,0 +1,24 @@
import _ from 'lodash';
export function isValidObjectId(objectId?: string): boolean {
return !_.isNil(objectId) && /^[0-9a-fA-F]{24}$/.test(objectId);
}
export function objectIdToDate(objectId: string): Date {
return new Date(Number.parseInt(objectId.substring(0, 8), 16) * 1000);
}
export function objectIdFromDate(milliseconds: number, onlyDate: boolean = false): string {
const suffixReplacer = () => {
if (onlyDate) {
return '0';
}
return (Math.random() * 16 | 0).toString(16);
};
const timestamp = (milliseconds / 1000 | 0).toString(16);
const suffix = 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, suffixReplacer).toLowerCase();
return `${timestamp}${suffix}`;
}