Skip to content

Commit ecfa052

Browse files
committed
docs: document all remaining utils
1 parent 8617ea4 commit ecfa052

File tree

6 files changed

+238
-5
lines changed

6 files changed

+238
-5
lines changed

src/array.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export function firstOrSelf<T>(value: Maybe<Arrayable<T>>): Optional<T> {
3030
*
3131
* ```ts
3232
* intersperse(['a', 'b', 'c'], '-'); // ['a', '-', 'b', '-', 'c']
33+
* ```
3334
*/
3435
export function intersperse<T>(array: ReadonlyArray<T>, separator: T): T[] {
3536
return [...Array(2 * array.length - 1)].map((_, i) =>

src/date.ts

Lines changed: 77 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,44 @@
11
import type { Tagged } from 'type-fest';
22
import type { Maybe, Optional } from './types.js';
33

4+
/**
5+
* Represents a valid Date object.
6+
* This type is used to ensure that the date is a valid instance of Date and not an invalid date.
7+
*/
48
export type ValidDate = Tagged<Date, 'valid'>;
59

10+
/**
11+
* Checks if a value is a valid Date object.
12+
*
13+
* ```ts
14+
* isValidDate(new Date()); // true
15+
* isValidDate(new Date('2023-10-01')); // true
16+
* isValidDate(new Date('invalid-date')); // false
17+
* isValidDate('2023-10-01'); // false
18+
* ```
19+
*/
620
export function isValidDate(date: Date): date is ValidDate {
721
return date instanceof Date && !Number.isNaN(date.getTime());
822
}
923

24+
/**
25+
* Gets the date string in ISO format (YYYY-MM-DD) from a Date object or a date-like value.
26+
*
27+
* ```ts
28+
* getDateString(new Date('2023-10-01')); // '2023-10-01'
29+
* getDateString('2023-10-01'); // '2023-10-01'
30+
* getDateString(1738358400000); // '2023-10-01'
31+
* getDateString(new Date('invalid-date')); // undefined
32+
* getDateString(null); // undefined
33+
* getDateString(undefined); // undefined
34+
* ```
35+
*/
1036
export function getDateString(date: ValidDate): string;
1137
export function getDateString(
12-
date?: Maybe<Date | string | number>,
38+
date: Maybe<Date | string | number>,
1339
): Optional<string>;
1440
export function getDateString(
15-
date?: Maybe<Date | string | number>,
41+
date: Maybe<Date | string | number>,
1642
): Optional<string> {
1743
if (date == null) return undefined;
1844

@@ -25,12 +51,24 @@ export function getDateString(
2551
return date.toISOString().split('T')[0];
2652
}
2753

54+
/**
55+
* Gets the date and time string in ISO format (YYYY-MM-DDTHH:mm:ss) from a Date object or a date-like value.
56+
*
57+
* ```ts
58+
* getDateTimeString(new Date('2023-10-01T12:34:56')); // '2023-10-01T12:34:56'
59+
* getDateTimeString('2023-10-01T12:34:56'); // '2023-10-01T12:34:56'
60+
* getDateTimeString(1738358400000); // '2023-10-01T00:00:00'
61+
* getDateTimeString(new Date('invalid-date')); // undefined
62+
* getDateTimeString(null); // undefined
63+
* getDateTimeString(undefined); // undefined
64+
* ```
65+
*/
2866
export function getDateTimeString(date: ValidDate): string;
2967
export function getDateTimeString(
30-
date?: Maybe<Date | string | number>,
68+
date: Maybe<Date | string | number>,
3169
): Optional<string>;
3270
export function getDateTimeString(
33-
date?: Maybe<Date | string | number>,
71+
date: Maybe<Date | string | number>,
3472
): Optional<string> {
3573
if (date == null) return undefined;
3674

@@ -43,12 +81,34 @@ export function getDateTimeString(
4381
return date.toISOString().split('.')[0];
4482
}
4583

46-
export function toDate(value: Maybe<string | number | Date>) {
84+
/**
85+
* Converts a value to a Date object.
86+
*
87+
* ```ts
88+
* toDate('2023-10-01'); // Date object for October 1, 2023
89+
* toDate(1738358400000); // Date object for October 1, 2023
90+
* toDate(new Date('2023-10-01')); // Date object for October 1, 2023
91+
* toDate('invalid-date'); // undefined
92+
* toDate(null); // undefined
93+
* toDate(undefined); // undefined
94+
* ```
95+
*/
96+
export function toDate(value: Maybe<string | number | Date>): Date | undefined {
4797
if (value == null) return undefined;
4898
const date = new Date(value);
4999
return Number.isNaN(date.getTime()) ? undefined : date;
50100
}
51101

102+
/**
103+
* Checks if a date is between two other dates (inclusive).
104+
*
105+
* ```ts
106+
* isBetween(new Date('2023-10-01'), new Date('2023-09-01'), new Date('2023-11-01')); // true
107+
* isBetween(new Date('2023-10-01'), new Date('2023-10-01'), new Date('2023-10-01')); // true
108+
* isBetween(new Date('2023-10-01'), new Date('2023-11-01'), new Date('2023-09-01')); // false
109+
* isBetween(new Date('2023-10-01'), new Date('2023-10-02'), new Date('2023-10-02')); // false
110+
* ```
111+
*/
52112
export function isBetween(date: Date, min: Date, max: Date): boolean {
53113
return min <= date && date <= max;
54114
}
@@ -58,6 +118,18 @@ const defaultOptions: Intl.DateTimeFormatOptions = {
58118
timeStyle: 'short',
59119
};
60120

121+
/**
122+
* Formats a date into a string using the specified locales and options.
123+
*
124+
* ```ts
125+
* formatDate(new Date('2023-10-01'), { locales: 'en-US', options: { dateStyle: 'full' } }); // "Sunday, October 1, 2023"
126+
* formatDate('2023-10-01', { locales: 'fr-FR', options: { dateStyle: 'long' } }); // "1 octobre 2023"
127+
* formatDate(1738358400000, { locales: 'de-DE', options: { timeStyle: 'short' } }); // "01.10.2023, 00:00"
128+
* formatDate(new Date('invalid-date')); // "Invalid Date"
129+
* formatDate(null); // undefined
130+
* formatDate(undefined); // undefined
131+
* ```
132+
*/
61133
export function formatDate(
62134
date: Maybe<string | number | Date>,
63135
params?: {

src/function.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,85 @@
1+
/**
2+
* No operation function.
3+
* This is a utility function that does nothing when called. It can be used as a placeholder
4+
* or default callback when no action is needed.
5+
*
6+
* ```ts
7+
* noop(); // Does nothing
8+
* ```
9+
*
10+
* @deprecated Use `noop` from `es-toolkit` instead.
11+
*/
112
export function noop() {}
213

14+
/**
15+
* Returns the input value.
16+
* This is a utility function that can be used as a default callback or placeholder
17+
* when no transformation is needed. It simply returns the value passed to it.
18+
*
19+
* ```ts
20+
* const value = 42;
21+
* const result = identity(value);
22+
* console.log(result); // 42
23+
* ```
24+
*
25+
* @deprecated Use `identity` from `es-toolkit` instead.
26+
*/
327
export function identity<T>(value: T): T {
428
return value;
529
}
630

31+
/**
32+
* Returns false.
33+
* This is a utility function that can be used as a default callback or placeholder
34+
* when a false value is needed. It simply returns `false`.
35+
*
36+
* ```ts
37+
* const result = falseFn();
38+
* console.log(result); // false
39+
* ```
40+
*/
741
export function falseFn() {
842
return false;
943
}
1044

45+
/**
46+
* Returns true.
47+
* This is a utility function that can be used as a default callback or placeholder
48+
* when a true value is needed. It simply returns `true`.
49+
*
50+
* ```ts
51+
* const result = trueFn();
52+
* console.log(result); // true
53+
* ```
54+
*/
1155
export function trueFn() {
1256
return true;
1357
}
1458

59+
/**
60+
* Returns null.
61+
* This is a utility function that can be used as a default callback or placeholder
62+
* when a null value is needed. It simply returns `null`.
63+
*
64+
* ```ts
65+
* const result = nullFn();
66+
* console.log(result); // null
67+
* ```
68+
*/
1569
export function nullFn() {
1670
return null;
1771
}
1872

73+
/**
74+
* Returns undefined.
75+
* This is a utility function that can be used as a default callback or placeholder
76+
* when an undefined value is needed. It simply returns `undefined`.
77+
*
78+
* ```ts
79+
* const result = undefinedFn();
80+
* console.log(result); // undefined
81+
* ```
82+
*/
1983
export function undefinedFn() {
2084
return undefined;
2185
}

src/promise.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,62 @@
1+
/**
2+
* Checks if a promise result is rejected.
3+
* Can be used as a type guard to narrow the type of the result to `PromiseRejectedResult`.
4+
*
5+
* ```ts
6+
* const rejected = new Promise((_, reject) => setTimeout(() => reject(new Error('fail')), 1000));
7+
* const result = await settled(rejected);
8+
* console.log(isRejected(result)); // true
9+
*
10+
* const results = await Promise.allSettled([
11+
* Promise.resolve('done'),
12+
* Promise.reject(new Error('fail')),
13+
* ]);
14+
* console.log(results.filter(isRejected)); // [{ status: 'rejected', reason: Error('fail') }]
15+
* console.log(results.filter(isFulfilled)); // [{ status: 'fulfilled', value: 'done' }]
16+
* ```
17+
*/
118
export function isRejected<T>(
219
result: PromiseSettledResult<T>,
320
): result is PromiseRejectedResult {
421
return result.status === 'rejected';
522
}
623

24+
/**
25+
* Checks if a promise result is fulfilled.
26+
* Can be used as a type guard to narrow the type of the result to `PromiseFulfilledResult`.
27+
*
28+
* ```ts
29+
* const fulfilled = new Promise((resolve) => setTimeout(() => resolve('done'), 1000));
30+
* const result = await settled(fulfilled);
31+
* console.log(isFulfilled(result)); // true
32+
*
33+
* const results = await Promise.allSettled([
34+
* Promise.resolve('done'),
35+
* Promise.reject(new Error('fail')),
36+
* ]);
37+
* console.log(results.filter(isFulfilled)); // [{ status: 'fulfilled', value: 'done' }]
38+
* console.log(results.filter(isRejected)); // [{ status: 'rejected', reason: Error('fail') }]
39+
* ```
40+
*/
741
export function isFulfilled<T>(
842
result: PromiseSettledResult<T>,
943
): result is PromiseFulfilledResult<T> {
1044
return result.status === 'fulfilled';
1145
}
1246

47+
/**
48+
* Returns the first settled result of a promise.
49+
*
50+
* ```ts
51+
* const fulfilled = new Promise((resolve) => setTimeout(() => resolve('done'), 1000));
52+
* const result = await settled(fulfilled);
53+
* console.log(result); // { status: 'fulfilled', value: 'done' }
54+
*
55+
* const rejected = new Promise((_, reject) => setTimeout(() => reject(new Error('fail')), 1000));
56+
* const result = await settled(rejected);
57+
* console.log(result); // { status: 'rejected', reason: Error('fail') }
58+
* ```
59+
*/
1360
export async function settled<T>(
1461
promise: Promise<T>,
1562
): Promise<PromiseSettledResult<T>> {
@@ -29,6 +76,17 @@ export type Failure<E> = [null, E] & {
2976

3077
export type Result<T, E = Error> = Success<T> | Failure<E>;
3178

79+
/**
80+
* Tries to resolve a promise and returns a result tuple.
81+
* Similar to {@link settled}, but returns a tuple with the data and error.
82+
*
83+
* ```ts
84+
* const result = await tryCatch(Promise.resolve('success'));
85+
* console.log(result); // ['success', null]
86+
* const errorResult = await tryCatch(Promise.reject(new Error('fail')));
87+
* console.log(errorResult); // [null, Error('fail')]
88+
* ```
89+
*/
3290
export async function tryCatch<T, E = Error>(
3391
promise: Promise<T>,
3492
): Promise<Result<T, E>> {

src/types.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
/**
2+
* Strictly omits keys from an object type.
3+
*/
14
export type StrictOmit<T, K extends keyof T> = Omit<T, K>;
25

36
export type Optional<T> = T | undefined;
@@ -29,6 +32,9 @@ export type Choice<T extends ID = ID> = {
2932
children?: ReadonlyArray<Choice<T>>;
3033
};
3134

35+
/**
36+
* A read-only array type that ensures all elements are read-only.
37+
*/
3238
export type ReadonlyArrayStrict<T> = ReadonlyArray<Readonly<T>>;
3339

3440
export type DeepWriteable<T> = {

src/utils.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,42 @@
1+
/**
2+
* Utility functions for type checking in JavaScript.
3+
* These functions help determine the type of a value at runtime.
4+
*
5+
* ```ts
6+
* isType('hello', 'string'); // true
7+
* isType(42, 'number'); // true
8+
* isType(true, 'boolean'); // true
9+
* isType([], 'array'); // true
10+
* isType({}, 'object'); // true
11+
* isType(null, 'null'); // true
12+
* isType(undefined, 'undefined'); // true
13+
*/
114
export function isType<T extends keyof TypeMap>(
215
value: unknown,
316
type: T,
417
): value is TypeMap[T] {
518
return getType(value) === type;
619
}
720

21+
/**
22+
* Returns the type of a value as a string.
23+
* This function uses `Object.prototype.toString` to determine the type of the value.
24+
* It returns a lowercase string representing the type, such as "string", "number", "boolean", etc.
25+
*
26+
* ```ts
27+
* getType('hello'); // 'string'
28+
* getType(42); // 'number'
29+
* getType(true); // 'boolean'
30+
* getType([]); // 'array'
31+
* getType({}); // 'object'
32+
* getType(null); // 'null'
33+
* getType(undefined); // 'undefined'
34+
* getType(new Date()); // 'date'
35+
* getType(/regex/); // 'regexp'
36+
* getType(new Map()); // 'map'
37+
* getType(new Set()); // 'set'
38+
* getType(new Promise(() => {})); // 'promise'
39+
*/
840
export function getType(value: unknown): keyof TypeMap | (string & {}) {
941
const s = Object.prototype.toString.call(value);
1042
return s.slice(8, -1).toLowerCase();

0 commit comments

Comments
 (0)