-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmaybe.ts
More file actions
22 lines (21 loc) · 620 Bytes
/
maybe.ts
File metadata and controls
22 lines (21 loc) · 620 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import type { Predicate } from "./type.ts";
/**
* Returns the input value if it satisfies the provided predicate, or `undefined` otherwise.
*
* ```ts
* import { is, maybe } from "@core/unknownutil";
*
* const a: unknown = "hello";
* const _: string = maybe(a, is.String) ?? "default value";
* ```
*
* @param x The value to be tested.
* @param pred The predicate function to test the value against.
* @returns The input value `x` if it satisfies the predicate, or `undefined` otherwise.
*/
export function maybe<T>(
x: unknown,
pred: Predicate<T>,
): T | undefined {
return pred(x) ? x : undefined;
}