-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoption.ts
247 lines (228 loc) · 7.46 KB
/
option.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { isMatching, P } from "npm:ts-pattern@5.1.1";
/**
* Represents an optional value, either `Some` containing a value or `None`.
* @template Thing - The type of the value.
*/
export type Option<Thing> = Some<Thing> | None;
/**
* Represents an optional value that contains a value.
* @template Thing - The type of the value.
*/
export type Some<Thing> = {
readonly isSome: true;
readonly data: Thing;
readonly isNone: false;
};
/**
* Represents an optional value that does not contain a value.
*/
export type None = {
readonly isSome: false;
readonly data: undefined;
readonly isNone: true;
};
/**
* Creates an instance of Some.
* @template Thing - The type of the value.
* @param {Thing} data - The value to be contained.
* @returns {Some<Thing>} An instance of Some.
*/
export const some = <Thing>(data: Thing): Some<Thing> => {
return { isSome: true, data, isNone: false } as Some<Thing>;
};
/**
* Represents a constant `Some` with any type of data.
*/
export const SOMETHING: {
readonly isSome: true;
readonly isNone: false;
readonly data: any;
} = {
isSome: true,
isNone: false,
data: P.select(),
} as const;
/**
* Represents a constant `None`.
*/
export const NOTHING: None = { isSome: false, isNone: true } as None;
/**
* Wraps a function call in a promise that resolves to an Option.
* @template F - The type of the function.
* @param {F} someFunction - The function to wrap.
* @returns {Promise<Option<NonNullable<Awaited<ReturnType<F>>>>>} A promise resolving to an Option.
*/
export function OptionOf<F extends (...args: any[]) => any>(
someFunction: F
): Promise<Option<NonNullable<Awaited<ReturnType<F>>>>> {
return new Promise((resolve) => {
try {
return someFunction()
.then((res: any) => resolve(optionOfThing(res)))
.catch(() => resolve(NOTHING));
} catch (e: unknown) {
try {
const thing = someFunction();
return resolve(optionOfThing(thing));
} catch (e) {
return resolve(NOTHING);
}
}
});
}
/**
* Represents the Some variant type.
* @template R - The type of the option.
*/
export type SomeVariant<R extends Option<unknown>> = R extends Some<unknown>
? R
: never;
/**
* Utility object for creating and managing Option types.
*/
export const Option = {
some,
SOMETHING,
NOTHING,
OptionOf,
};
/**
* Converts a value to an Option.
* @template T - The type of the value.
* @param {T} data - The value to convert.
* @returns {Option<T>} An Option containing the value.
*/
const optionOfThing = <T>(data: T): Option<T> => {
const thingIsNullish = data === null || data === undefined;
const thingIsEmptyArray = Array.isArray(data) && !data.length;
const thingIsEmptyString = data === "";
const thingIsNothing = isMatching(NOTHING, data);
if (
thingIsNullish ||
thingIsEmptyArray ||
thingIsNothing ||
thingIsEmptyString
) {
return NOTHING;
}
const thingIsOption = isMatching(SOMETHING, data);
if (thingIsOption) {
return data as unknown as Some<T>;
} else {
return some(data);
}
};
// This library provides a way to represent values that may or may not exist. It does this by introducing the Option type, which can be either a Some variant, representing a value that is present, or a Nothing variant, representing a value that is not present.
//
// Why this is useful?
//
// By using Option and its variants, you can more clearly express the intent of your code and ensure that your program is handling the presence or absence of a value correctly.
//
//
//
// Examples
//
// const getName = (foo: string): Option<string> => {
// const match = foo.match(/bar/g);
// if (!match) {
// return NOTHING;
// } else {
// return some(match[0]);
// }
// };
// By doing this you explicitly communicate to the callers of this function that it might return nothing.
// This, of course, means that we must know that when we use the `match` String method that we may get nothing back. This is an example of what it looks like to manifest the discipline needed to write robust, safe code.
//
// // Here we see an example of how we gain access to the value we want;
// const printName = (maybeName: Option<string>) => {
// if (isSome(maybeName)) {
// const { data: name } = maybeName;
// printString(name);
// } else {
// printString("oopsie poopsie");
// }
// };
//
// We can rewrite this to be both more explicit and more concise by using the ts-pattern library to pattern match against Option variants Some<Thing> (with the pre-defined pattern SOMETHING) and/or Nothing (with the pre-defined pattern NOTHING).
//
// const printName = (maybeName: Option<string>) =>
// printString(
// match(maybeName)
// .with(SOMETHING, (name) => name)
// .otherwise(() => "oopsie poopsie")
// );
//
// But we can talk about that later.
//
// const printString = (name: string) => {
// console.log(name);
// };
//
// const maybeName = await getName();
//
// printString(maybeName); //typescript: Argument of type 'Option<QueryResult>' is not assignable to parameter of type 'string'.
//
// printName(maybeName);
//
//
//
//
//
//
// The OptionOf function is a convenience function that allows you to wrap a function call in a promise that will resolve to an Option, making it easier to handle the case where the function may return an nullish value;
// Note: In the case where you want to check if something is null, undefined, an empty array, or an empty object you can use the convenince function OptionOf and wrap the value in a closure as the parameter to the convenience function. This will return a promise so that it can handle both async and sync functions. This means youll always have to include `await` and this also means its enclosing function will need to be async. A lopsided exchange in convenience in my view.
//
// const getName = await OptionOf(() => ["foo"].find((el) => el === "bar"));
//
//
//
// In the scenario where you have a high level function utilizing multiple lower level functions that may return nullish values, writing those functions to take Options of type T as their parameters instead of type T directly allows you to hide nullish checks in those functions to reduce the length of high level functions.
//
// More importantly though, it allows us to reduce the breadth of abstractions by allowing us to write these high level functions that "do a lot" in a clear and concise way such that we dont have to break that high level function up into multiple medium-level abstractions that are less intuitive to name, let alone understand. Observe:
//
// // Instead of having to think about breaking this monstrosity up into multiple abstract functions:
//
// function longHighLevelFunction() {
// const foo = getFoo();
// if (foo) {
// const bar = getBar(foo);
// if (bar) {
// const baz = getBaz(bar);
// if (baz) {
// // ...
// } else {
// //...
// }
// } else {
// //...
// }
// } else {
// //...
// }
// }
//
// // Or even this:
//
// function longHighLevelFunction() {
// const foo = getFoo();
// if (!foo) {
// //...
// }
// const bar = getBar(foo);
// if (!bar) {
// //...
// }
// const baz = getBaz(bar);
// if (!baz) {
// //...
// }
// //...
// }
//
// // We can simply write this:
// function highLevelFunction() {
// const maybeFoo = getFoo();
// const maybeBar = getBar(maybeFoo);
// const maybeBaz = getBar(maybeBar);
// //...
// }