name:
src/main/js/common/utils/Optional.ts
-rw-r--r--
1470
1import { isUndefined } from "./Types";
2
3/**
4 * Similar to Java's Optional. Better than using null, or undefined.
5 */
6
7export class Optional<T> {
8 private value: T | any = null;
9
10 constructor(value?: T) {
11 this.value = value;
12 }
13
14 /**
15 * Create new Optional with the value. If the value is null will result in the same Optional as Optional.empty().
16 * @param value
17 */
18 static of<T>(value: T): Optional<T> {
19 return new Optional<T>(value);
20 }
21
22 /**
23 * Create new, empty optional.
24 */
25 static empty<T>(): Optional<T> {
26 return new Optional<T>();
27 }
28
29 /**
30 * Is the value in this Optional present, and non-null, and non-undefined?
31 */
32 isPresent(): boolean {
33 return !this.isEmpty();
34 }
35
36 /**
37 * Is the value in this Optional absent or null or undefined?
38 */
39 isEmpty(): boolean {
40 return this.value === null || isUndefined(this.value);
41 }
42
43 /**
44 * Get the value in this Optional. If the value is null or undefined, will return null or undefined.
45 */
46 get(): T {
47 return this.value;
48 }
49
50 /**
51 * If the value of this Optional is empty, null, or undefined, will return a given default value.
52 * @param defaultValue
53 */
54 getOrDefault(defaultValue: T): T {
55 return this.isEmpty() ? defaultValue : this.value;
56 }
57
58 /**
59 * Easy way to render what the value is, and indicate that this is an Optional.
60 */
61 public toString(): string {
62 return `Optional[${this.isEmpty() ? "null" : this.value}]`;
63 }
64}