-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdataUtils.ts
More file actions
55 lines (50 loc) · 1.52 KB
/
dataUtils.ts
File metadata and controls
55 lines (50 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import type { NonEmptyArray } from '../types';
/**
* Returns a date string formatted for use in a file path.
* The format is YYYYMMDDTHHMMSSZ.
* @param dateOrIsoString A Date object or an ISO 8601 date string.
* @returns A string formatted for use in a file path.
*/
export function getFilePathDateToken(
dateOrIsoString: Date | string = new Date()
): string {
if (dateOrIsoString instanceof Date) {
dateOrIsoString = dateOrIsoString.toISOString();
}
return `${dateOrIsoString.substring(0, 19).replace(/[:-]/g, '')}Z`;
}
/**
* Type guard to determine if an object has a property.
* @param obj The object to check.
* @param prop The property to check for.
* @returns true if the property exists, false otherwise.
*/
export function hasProperty<TProp extends string>(
obj: unknown,
prop: TProp
): obj is Record<TProp, unknown> {
return obj != null && typeof obj === 'object' && prop in obj;
}
/**
* Type guard to check if an array is non-empty.
* @param array
* @returns true if the array is non-empty, false otherwise
*/
export function isNonEmptyArray<T>(array: T[]): array is NonEmptyArray<T> {
return array.length > 0;
}
/**
* Create a sort comparator function that compares a stringified property on
* 2 objects.
* @param propName Prop to compare
*/
export function sortByStringProp<TPropName extends string>(
propName: TPropName
) {
return <TValue extends { [P in TPropName]: unknown }>(
a: TValue,
b: TValue
): number => {
return String(a[propName]).localeCompare(String(b[propName]));
};
}