mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-04-24 16:56:14 -04:00
add objectid util functions
This commit is contained in:
parent
64082d4e6d
commit
7e5e4d00ee
3 changed files with 28 additions and 5 deletions
24
src/utils/objectId.ts
Normal file
24
src/utils/objectId.ts
Normal 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}`;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue