@carbonteq/fp 0.8.0-alpha.5 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +270 -49
- package/dist/chunk-CUT6urMc.cjs +30 -0
- package/dist/index.cjs +13 -664
- package/dist/index.d.cts +5 -190
- package/dist/index.d.ts +5 -190
- package/dist/index.js +5 -650
- package/dist/match-BQP0RNSk.js +13 -0
- package/dist/match-BQP0RNSk.js.map +1 -0
- package/dist/match-COIWq-e8.d.cts +18 -0
- package/dist/match-COIWq-e8.d.cts.map +1 -0
- package/dist/match-DXKW7ym5.d.ts +18 -0
- package/dist/match-DXKW7ym5.d.ts.map +1 -0
- package/dist/match-DyAuOeqx.cjs +25 -0
- package/dist/match-DyAuOeqx.cjs.map +1 -0
- package/dist/match.cjs +4 -0
- package/dist/match.d.cts +5 -0
- package/dist/match.d.ts +5 -0
- package/dist/match.js +3 -0
- package/dist/option-8_eiz02z.d.cts +45 -0
- package/dist/option-8_eiz02z.d.cts.map +1 -0
- package/dist/option-Be_DXVE6.js +181 -0
- package/dist/option-Be_DXVE6.js.map +1 -0
- package/dist/option-CoelyMEg.d.ts +45 -0
- package/dist/option-CoelyMEg.d.ts.map +1 -0
- package/dist/option-DHCdfOco.cjs +193 -0
- package/dist/option-DHCdfOco.cjs.map +1 -0
- package/dist/option.cjs +5 -0
- package/dist/option.d.cts +3 -0
- package/dist/option.d.ts +3 -0
- package/dist/option.js +4 -0
- package/dist/result-CdGWA5IL.js +318 -0
- package/dist/result-CdGWA5IL.js.map +1 -0
- package/dist/result-DsVjSFnO.d.ts +132 -0
- package/dist/result-DsVjSFnO.d.ts.map +1 -0
- package/dist/result-Dy_C5dC6.d.cts +132 -0
- package/dist/result-Dy_C5dC6.d.cts.map +1 -0
- package/dist/result-nuhyCRyu.cjs +336 -0
- package/dist/result-nuhyCRyu.cjs.map +1 -0
- package/dist/result.cjs +6 -0
- package/dist/result.d.cts +3 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +4 -0
- package/dist/tuple.cjs +14 -0
- package/dist/tuple.cjs.map +1 -0
- package/dist/tuple.d.cts +12 -0
- package/dist/tuple.d.cts.map +1 -0
- package/dist/tuple.d.ts +12 -0
- package/dist/tuple.d.ts.map +1 -0
- package/dist/tuple.js +12 -0
- package/dist/tuple.js.map +1 -0
- package/dist/unit-CnjFzJN1.cjs +12 -0
- package/dist/unit-CnjFzJN1.cjs.map +1 -0
- package/dist/unit-CoBLIJFc.d.ts +9 -0
- package/dist/unit-CoBLIJFc.d.ts.map +1 -0
- package/dist/unit-D0y_qAUW.d.cts +9 -0
- package/dist/unit-D0y_qAUW.d.cts.map +1 -0
- package/dist/unit-udy5j53P.js +6 -0
- package/dist/unit-udy5j53P.js.map +1 -0
- package/dist/unit.cjs +3 -0
- package/dist/unit.d.cts +2 -0
- package/dist/unit.d.ts +2 -0
- package/dist/unit.js +3 -0
- package/package.json +23 -25
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -68,7 +68,9 @@ function getUserAddress(user: { email?: string }): Option<string> {
|
|
|
68
68
|
return user.email ? Option.Some("Some Address") : Option.None;
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
-
const res = getUserByEmail({ email: "test@test.com" }).flatZip((email) =>
|
|
71
|
+
const res = getUserByEmail({ email: "test@test.com" }).flatZip((email) =>
|
|
72
|
+
getUserAddress({ email }),
|
|
73
|
+
);
|
|
72
74
|
|
|
73
75
|
matchOpt(res, {
|
|
74
76
|
Some: (res) => {
|
|
@@ -94,8 +96,7 @@ matchOpt(res, {
|
|
|
94
96
|
- [Comparison of map and zip](#comparison-of-map-flatmap-zip-and-flatzip)
|
|
95
97
|
- [Some Other Useful Functions](#some-other-useful-functions)
|
|
96
98
|
- [mapErr](#maperr)
|
|
97
|
-
- [mapOr](#mapor)
|
|
98
|
-
- [tap](#tap)
|
|
99
|
+
- [mapOr](#mapor) <!-- - [tap](#tap) -->
|
|
99
100
|
- [all](#all)
|
|
100
101
|
- [validate](#validate)
|
|
101
102
|
- [unwrap](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
|
|
@@ -145,7 +146,9 @@ Let's say we want to apply a 10% bonus to the account balance of a user.
|
|
|
145
146
|
```typescript
|
|
146
147
|
import { Option } from "@carbonteq/fp";
|
|
147
148
|
|
|
148
|
-
async function fetchUserBalanceFromDatabase(
|
|
149
|
+
async function fetchUserBalanceFromDatabase(
|
|
150
|
+
userId: string,
|
|
151
|
+
): Promise<Option<number>> {
|
|
149
152
|
// Simulate fetching balance from a database
|
|
150
153
|
await Promise.resolve(userId);
|
|
151
154
|
return Option.Some(100);
|
|
@@ -173,7 +176,10 @@ Let's say we want to validate user input and then save it to a database:
|
|
|
173
176
|
import { Result } from "@carbonteq/fp";
|
|
174
177
|
|
|
175
178
|
// Function to validate user input
|
|
176
|
-
const validateUserData = (
|
|
179
|
+
const validateUserData = (
|
|
180
|
+
name: string,
|
|
181
|
+
age: number,
|
|
182
|
+
): Result<{ name: string; age: number }, Error> => {
|
|
177
183
|
if (name.trim() === "") {
|
|
178
184
|
return Result.Err(new Error("Name cannot be empty"));
|
|
179
185
|
}
|
|
@@ -184,15 +190,23 @@ const validateUserData = (name: string, age: number): Result<{ name: string; age
|
|
|
184
190
|
};
|
|
185
191
|
|
|
186
192
|
// Simulated asynchronous task to save user data to a "database"
|
|
187
|
-
const saveUserData = async (user: {
|
|
193
|
+
const saveUserData = async (user: {
|
|
194
|
+
name: string;
|
|
195
|
+
age: number;
|
|
196
|
+
}): Promise<Result<string, Error>> => {
|
|
188
197
|
// Simulate saving to database
|
|
189
198
|
await Promise.resolve(user);
|
|
190
199
|
return Result.Ok(`User ${user.name} saved successfully!`);
|
|
191
200
|
};
|
|
192
201
|
|
|
193
202
|
// Chaining validation and save using `flatMap`
|
|
194
|
-
const processUser = async (
|
|
195
|
-
|
|
203
|
+
const processUser = async (
|
|
204
|
+
name: string,
|
|
205
|
+
age: number,
|
|
206
|
+
): Promise<Result<string, Error>> => {
|
|
207
|
+
const validationResult = await validateUserData(name, age)
|
|
208
|
+
.flatMap(saveUserData)
|
|
209
|
+
.toPromise();
|
|
196
210
|
return validationResult;
|
|
197
211
|
};
|
|
198
212
|
|
|
@@ -209,13 +223,17 @@ For example, suppose we want to pair the product's original price `T` and discou
|
|
|
209
223
|
```typescript
|
|
210
224
|
import { Result } from "@carbonteq/fp";
|
|
211
225
|
|
|
212
|
-
async function fetchProductPrice(
|
|
226
|
+
async function fetchProductPrice(
|
|
227
|
+
productId: string,
|
|
228
|
+
): Promise<Result<number, Error>> {
|
|
213
229
|
// Simulate fetching price from a database
|
|
214
230
|
await Promise.resolve(productId);
|
|
215
231
|
return Result.Ok(100);
|
|
216
232
|
}
|
|
217
233
|
|
|
218
|
-
async function applyDiscount(
|
|
234
|
+
async function applyDiscount(
|
|
235
|
+
productId: string,
|
|
236
|
+
): Promise<Result<[number, number], Error>> {
|
|
219
237
|
const originalPrice = await Result.Ok(productId)
|
|
220
238
|
.flatMap(fetchProductPrice)
|
|
221
239
|
.zip((price) => price * 0.9)
|
|
@@ -252,8 +270,13 @@ async function fetchProductStock(productId: string): Promise<Option<number>> {
|
|
|
252
270
|
}
|
|
253
271
|
|
|
254
272
|
// Function to combine price and stock using flatZip
|
|
255
|
-
async function fetchProductDetails(
|
|
256
|
-
|
|
273
|
+
async function fetchProductDetails(
|
|
274
|
+
productId: string,
|
|
275
|
+
): Promise<Option<[number, number]>> {
|
|
276
|
+
const productDetails = await Option.Some(productId)
|
|
277
|
+
.flatMap(fetchProductPrice)
|
|
278
|
+
.flatZip(fetchProductStock)
|
|
279
|
+
.toPromise();
|
|
257
280
|
return productDetails; // Option<[number, number]>
|
|
258
281
|
}
|
|
259
282
|
|
|
@@ -262,8 +285,8 @@ console.log(await fetchProductDetails("123")); // Output: Option.Some([100, 50])
|
|
|
262
285
|
|
|
263
286
|
## Comparison of `map`, `flatMap`, `zip`, and `flatZip`
|
|
264
287
|
|
|
265
|
-
| **Method** | **`map`** | **`flatMap`** | **`zip`** | **`flatZip`** |
|
|
266
|
-
| --------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
|
|
288
|
+
| **Method** | **`map`** | **`flatMap`** | **`zip`** | **`flatZip`** |
|
|
289
|
+
| --------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
|
|
267
290
|
| **Purpose** | Transforms the value inside an `Ok` or `Some`. | Chains dependent computations where each computation returns a `Result` or `Option`. | Combines the current value with another derived value into a tuple `[T, U]`. | Combines two independent `Result` or `Option` values into a tuple `[T, U]`. |
|
|
268
291
|
| **Input** | A function `(val: T) => U`. | A function `(val: T) => Result<U, E2>` or `(val: T) => Option<U>` to transform the current value into another `Result` or `Option`. | A function `(val: T) => U` to derive a new value `U` from the current value `T`. | A function `(val: T) => Result<U, E2>` or `(val: T) => Option<U>` that returns another `Result` or `Option`. |
|
|
269
292
|
| **Output** | `Result<U, E>`, `Option<U>` | `Result<U, E>`, `Option<U>` | `Result<[T, U], E>`, `Option<[T, U]>` | `Result<[T, U], E>`, `Option<[T, U]>`. |
|
|
@@ -291,7 +314,9 @@ function divideNumbers(a: number, b: number): Result<number, Error> {
|
|
|
291
314
|
|
|
292
315
|
// A safe divide function that returns a Result with a string error message if the division by zero occurs, instead of throwing an exception
|
|
293
316
|
function safeDivide(a: number, b: number): Result<number, string> {
|
|
294
|
-
const res = divideNumbers(a, b).mapErr(
|
|
317
|
+
const res = divideNumbers(a, b).mapErr(
|
|
318
|
+
(err) => `Operation failed: ${err.message}`,
|
|
319
|
+
);
|
|
295
320
|
return res;
|
|
296
321
|
}
|
|
297
322
|
|
|
@@ -319,7 +344,10 @@ async function findUserById(id: number): Promise<Option<number>> {
|
|
|
319
344
|
|
|
320
345
|
// A safe function that returns a string error message if the user is not found, instead of throwing an exception
|
|
321
346
|
async function safeFindUserById(id: number): Promise<Option<string>> {
|
|
322
|
-
const res = (await findUserById(id)).mapOr(
|
|
347
|
+
const res = (await findUserById(id)).mapOr(
|
|
348
|
+
`User not found`,
|
|
349
|
+
(res) => `User: ${res}`,
|
|
350
|
+
);
|
|
323
351
|
return res;
|
|
324
352
|
}
|
|
325
353
|
|
|
@@ -328,7 +356,7 @@ console.log(await safeFindUserById(10)); // Some(User: 10)
|
|
|
328
356
|
console.log(await safeFindUserById(0)); // Some(User not found)
|
|
329
357
|
```
|
|
330
358
|
|
|
331
|
-
#### `tap`
|
|
359
|
+
<!-- #### `tap`
|
|
332
360
|
|
|
333
361
|
`tap` is used to perform side effects on the `Result`/`Option` value without altering its contents. It is useful for logging, auditing, debugging complex chains of operations etc.
|
|
334
362
|
|
|
@@ -360,38 +388,212 @@ const res = (await findUserById(1))
|
|
|
360
388
|
.mapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
|
|
361
389
|
|
|
362
390
|
console.log(res); // Result.Ok({ id: 1, balance: 90 })
|
|
363
|
-
```
|
|
391
|
+
``` -->
|
|
364
392
|
|
|
365
393
|
#### `all`
|
|
366
394
|
|
|
367
395
|
`all` is used to combine an array of Results. If any errors exist they are accumulated, else the values are accumulated.
|
|
368
396
|
|
|
369
397
|
```typescript
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
398
|
+
import { Result, matchRes } from "@carbonteq/fp";
|
|
399
|
+
|
|
400
|
+
type User = {
|
|
401
|
+
userId: string;
|
|
402
|
+
userName: string;
|
|
403
|
+
createdAt: Date | string;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
type Post = {
|
|
407
|
+
postId: string;
|
|
408
|
+
likes: number;
|
|
409
|
+
replies: number;
|
|
410
|
+
createdAt: Date | string;
|
|
411
|
+
author: User["userId"];
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
type Like = {
|
|
415
|
+
likeId: string;
|
|
416
|
+
postId: Post["postId"];
|
|
417
|
+
createdAt: Date | string;
|
|
418
|
+
likedBy: User["userId"];
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
type Reply = {
|
|
422
|
+
replyId: string;
|
|
423
|
+
postId: Post["postId"];
|
|
424
|
+
createdAt: Date | string;
|
|
425
|
+
author: User["userId"];
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
type Hash = string;
|
|
429
|
+
|
|
430
|
+
async function fetchUser(userId: string): Promise<Result<User, unknown>> {
|
|
431
|
+
return Result.Ok({
|
|
432
|
+
userId,
|
|
433
|
+
userName: "Functional Programmer",
|
|
434
|
+
createdAt: "2025-01-01",
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async function fetchPosts(userId: string): Promise<Result<Post[], string>> {
|
|
439
|
+
if (userId === "TRIAL_USER") {
|
|
440
|
+
return Result.Err("User has no posts!");
|
|
441
|
+
}
|
|
442
|
+
return Result.Ok([
|
|
443
|
+
{
|
|
444
|
+
postId: "1",
|
|
445
|
+
likes: 12,
|
|
446
|
+
replies: 3,
|
|
447
|
+
createdAt: "2025-01-01",
|
|
448
|
+
author: userId,
|
|
449
|
+
},
|
|
450
|
+
]);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
async function fetchLikes(userId: string): Promise<Result<Like[], unknown>> {
|
|
454
|
+
return Result.Ok([
|
|
455
|
+
{ likeId: "3", postId: "2", createdAt: "2025-01-01", likedBy: userId },
|
|
456
|
+
]);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
async function fetchReplies(userId: string): Promise<Result<Reply[], string>> {
|
|
460
|
+
if (userId === "TRIAL_USER") {
|
|
461
|
+
return Result.Err("User has no replies!");
|
|
462
|
+
}
|
|
463
|
+
return Result.Ok([
|
|
464
|
+
{
|
|
465
|
+
replyId: "1",
|
|
466
|
+
postId: "2",
|
|
467
|
+
data: "Nice post!",
|
|
468
|
+
createdAt: "2025-01-01",
|
|
469
|
+
author: userId,
|
|
470
|
+
},
|
|
471
|
+
]);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function generateHash(userId: string): Result<Hash, Error> {
|
|
475
|
+
return Result.Ok(`${userId}_HASH_VALUE`);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async function getUserData(userId: string) {
|
|
479
|
+
const userIdRes = Result.Ok(userId);
|
|
480
|
+
|
|
481
|
+
const user = userIdRes.flatMap(fetchUser);
|
|
482
|
+
const posts = userIdRes.flatMap(fetchPosts);
|
|
483
|
+
const likes = userIdRes.flatMap(fetchLikes);
|
|
484
|
+
const replies = userIdRes.flatMap(fetchReplies);
|
|
485
|
+
const hash = userIdRes.flatMap(generateHash);
|
|
486
|
+
|
|
487
|
+
const userData = await Result.all(
|
|
488
|
+
user, // Result<Promise<T>, E>
|
|
489
|
+
posts, // Result<Promise<T>, E>
|
|
490
|
+
likes, // Result<Promise<T>, E>
|
|
491
|
+
replies, // Result<Promise<T>, E>
|
|
492
|
+
hash, // Result<T, E>
|
|
493
|
+
).toPromise();
|
|
494
|
+
|
|
495
|
+
matchRes(userData, {
|
|
496
|
+
Ok(v) {
|
|
497
|
+
console.log(v);
|
|
498
|
+
},
|
|
499
|
+
Err(e) {
|
|
500
|
+
console.log(e);
|
|
501
|
+
},
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
await getUserData("USER_ID");
|
|
506
|
+
|
|
507
|
+
// [
|
|
508
|
+
// {
|
|
509
|
+
// userId: 'USER_ID',
|
|
510
|
+
// userName: 'Functional Programmer',
|
|
511
|
+
// createdAt: '2025-01-01'
|
|
512
|
+
// },
|
|
513
|
+
// [
|
|
514
|
+
// {
|
|
515
|
+
// postId: '1',
|
|
516
|
+
// likes: 12,
|
|
517
|
+
// replies: 3,
|
|
518
|
+
// createdAt: '2025-01-01',
|
|
519
|
+
// userId: 'USER_ID'
|
|
520
|
+
// }
|
|
521
|
+
// ],
|
|
522
|
+
// [ { postId: '2', createdAt: '2025-01-01', userId: 'USER_ID' } ],
|
|
523
|
+
// [
|
|
524
|
+
// {
|
|
525
|
+
// postId: '2',
|
|
526
|
+
// data: 'Nice post!',
|
|
527
|
+
// createdAt: '2025-01-01',
|
|
528
|
+
// userId: 'USER_ID'
|
|
529
|
+
// }
|
|
530
|
+
// ],
|
|
531
|
+
// 'USER_ID_HASH_VALUE'
|
|
532
|
+
// ]
|
|
533
|
+
|
|
534
|
+
await getUserData("TRIAL_USER");
|
|
535
|
+
|
|
536
|
+
// [ 'User has no posts!', 'User has no replies!' ]
|
|
374
537
|
```
|
|
375
538
|
|
|
376
539
|
#### `validate`
|
|
377
540
|
|
|
378
|
-
Built on top of `all`, `validate` is used to execute an array of validator functions in parallel. If all validations pass, the original value is retained. If any validations fail, the errors are accumulated.
|
|
541
|
+
Built on top of `all`, `validate` is used to execute an array of validator functions in parallel. If all validations pass, the original value is retained. If any validations fail, the errors are accumulated. Both synchronous and asynchronous computations are handled.
|
|
379
542
|
|
|
380
543
|
```typescript
|
|
381
544
|
import { Result } from "@carbonteq/fp";
|
|
382
545
|
|
|
383
|
-
function
|
|
384
|
-
return
|
|
546
|
+
function hasMinimumLength(password: string): Result<boolean, Error> {
|
|
547
|
+
return password.length < 8
|
|
548
|
+
? Result.Err(new Error("Password must be at least 8 characters"))
|
|
549
|
+
: Result.Ok(true);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function hasSpecialCharacters(password: string): Result<boolean, Error> {
|
|
553
|
+
const specialCharsRegex = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
|
|
554
|
+
return !specialCharsRegex.test(password)
|
|
555
|
+
? Result.Err(
|
|
556
|
+
new Error("Password must contain at least one special character"),
|
|
557
|
+
)
|
|
558
|
+
: Result.Ok(true);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Asynchronous validation function - checks if password is different from previous
|
|
562
|
+
async function isNotSameAsPrevious(
|
|
563
|
+
password: string,
|
|
564
|
+
): Promise<Result<boolean, Error>> {
|
|
565
|
+
// Simulate checking against a database of user's previous passwords
|
|
566
|
+
return new Promise<Result<boolean, Error>>((resolve) => {
|
|
567
|
+
setTimeout(() => {
|
|
568
|
+
// For demo purposes, we'll consider "password123!" as the previous password
|
|
569
|
+
if (password === "password123!") {
|
|
570
|
+
resolve(
|
|
571
|
+
Result.Err(
|
|
572
|
+
new Error("New password cannot be the same as previous password"),
|
|
573
|
+
),
|
|
574
|
+
);
|
|
575
|
+
} else {
|
|
576
|
+
resolve(Result.Ok(true));
|
|
577
|
+
}
|
|
578
|
+
}, 200); // simulate network delay
|
|
579
|
+
});
|
|
385
580
|
}
|
|
386
581
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
582
|
+
const validatedOk = Result.Ok("password321!").validate([
|
|
583
|
+
hasMinimumLength,
|
|
584
|
+
hasSpecialCharacters,
|
|
585
|
+
]);
|
|
586
|
+
console.log(validatedOk.unwrap()); // password321!
|
|
390
587
|
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
console.log(validatedErr.unwrapErr()); // [Error
|
|
588
|
+
const validatedErr = await Result.Ok("pword")
|
|
589
|
+
.validate([hasMinimumLength, hasSpecialCharacters])
|
|
590
|
+
.toPromise();
|
|
591
|
+
console.log(validatedErr.unwrapErr()); // [Error: Password must be at least 8 characters, Error: Password must contain at least one special character]
|
|
592
|
+
|
|
593
|
+
const validatedErrs = await Result.Ok("password123!")
|
|
594
|
+
.validate([hasMinimumLength, hasSpecialCharacters, isNotSameAsPrevious])
|
|
595
|
+
.toPromise();
|
|
596
|
+
console.log(validatedErrs.unwrapErr()); // [Error: New password cannot be the same as previous password]
|
|
395
597
|
```
|
|
396
598
|
|
|
397
599
|
#### `unwrap`, `safeUnwrapErr`, `unwrapOr`, `unwrapOrElse`, `safeUnwrap`, and `unwrapErr`
|
|
@@ -411,11 +613,8 @@ function divideNumbers(a: number, b: number): Result<number, Error> {
|
|
|
411
613
|
// Example usage of each function
|
|
412
614
|
let result = divideNumbers(10, 2);
|
|
413
615
|
console.log(result.unwrap()); // unwrap: 5 (Extracts the value from Result.Ok, throwing an error if it's Err.)
|
|
414
|
-
console.log(result.safeUnwrapErr()); // safeUnwrapErr: null (returns error if Err, null if Ok)
|
|
415
616
|
|
|
416
617
|
result = divideNumbers(10, 0);
|
|
417
|
-
console.log(result.unwrapOr(0)); // unwrapOr: 0 (Returns the contained value if Ok, or a default value if Err)
|
|
418
|
-
console.log(result.unwrapOrElse(() => 0)); // unwrapOrElse: 0 (Similar to unwrapOr, but the default value is generated by a function.)
|
|
419
618
|
console.log(result.safeUnwrap()); // safeUnwrap: null (Safely unwraps the value, returning null if it's an Err instead of throwing an error.)
|
|
420
619
|
|
|
421
620
|
const errorResult = Result.Err(new Error("Something went wrong"));
|
|
@@ -455,7 +654,9 @@ function guardOrder(order: Order): Result<Order, string> {
|
|
|
455
654
|
// Check product availability
|
|
456
655
|
function guardInventoryCheck(order: Order): Result<Order, string> {
|
|
457
656
|
const availableStock = 100; // Simulated stock
|
|
458
|
-
return order.quantity <= availableStock
|
|
657
|
+
return order.quantity <= availableStock
|
|
658
|
+
? Result.Ok(order)
|
|
659
|
+
: Result.Err(`Insufficient stock. Available: ${availableStock}`);
|
|
459
660
|
}
|
|
460
661
|
|
|
461
662
|
// Calculate order total
|
|
@@ -509,7 +710,8 @@ matchRes(result, {
|
|
|
509
710
|
Let's build an asynchronous pipeline for a user registration system that includes credentials verification and profile setup.
|
|
510
711
|
|
|
511
712
|
```typescript
|
|
512
|
-
import {
|
|
713
|
+
import { matchRes } from "@/match.js";
|
|
714
|
+
import { Result } from "@/result.js";
|
|
513
715
|
|
|
514
716
|
interface UserInput {
|
|
515
717
|
email: string;
|
|
@@ -524,27 +726,37 @@ interface UserProfile {
|
|
|
524
726
|
verificationStatus: "pending" | "verified";
|
|
525
727
|
}
|
|
526
728
|
|
|
527
|
-
// Validate email format
|
|
528
|
-
|
|
729
|
+
// Validate email format (synchronous)
|
|
730
|
+
function guardEmail(email: string): Result<string, string> {
|
|
529
731
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
530
|
-
return emailRegex.test(email)
|
|
732
|
+
return emailRegex.test(email)
|
|
733
|
+
? Result.Ok(email)
|
|
734
|
+
: Result.Err("Invalid email format");
|
|
531
735
|
}
|
|
532
736
|
|
|
533
737
|
// Check if email is already registered
|
|
534
|
-
async function guardEmailAvailability(
|
|
738
|
+
async function guardEmailAvailability(
|
|
739
|
+
email: string,
|
|
740
|
+
): Promise<Result<string, string>> {
|
|
535
741
|
// Simulate database check
|
|
536
742
|
await Promise.resolve(email);
|
|
537
743
|
const registeredEmails = ["existing@example.com"];
|
|
538
|
-
return !registeredEmails.includes(email)
|
|
744
|
+
return !registeredEmails.includes(email)
|
|
745
|
+
? Result.Ok(email)
|
|
746
|
+
: Result.Err("Email already registered");
|
|
539
747
|
}
|
|
540
748
|
|
|
541
|
-
// Validate password strength
|
|
542
|
-
|
|
543
|
-
return password.length >= 8
|
|
749
|
+
// Validate password strength (synchronous)
|
|
750
|
+
function guardPassword(password: string): Result<string, string> {
|
|
751
|
+
return password.length >= 8
|
|
752
|
+
? Result.Ok(password)
|
|
753
|
+
: Result.Err("Password must be at least 8 characters");
|
|
544
754
|
}
|
|
545
755
|
|
|
546
756
|
// Create user profile
|
|
547
|
-
async function createUserProfile(
|
|
757
|
+
async function createUserProfile(
|
|
758
|
+
input: UserInput,
|
|
759
|
+
): Promise<Result<UserProfile, string>> {
|
|
548
760
|
const userProfile: UserProfile = {
|
|
549
761
|
userId: `USER-${Date.now()}`,
|
|
550
762
|
email: input.email,
|
|
@@ -555,7 +767,9 @@ async function createUserProfile(input: UserInput): Promise<Result<UserProfile,
|
|
|
555
767
|
}
|
|
556
768
|
|
|
557
769
|
// Send verification email
|
|
558
|
-
async function sendVerificationEmail(
|
|
770
|
+
async function sendVerificationEmail(
|
|
771
|
+
profile: UserProfile,
|
|
772
|
+
): Promise<Result<UserProfile, string>> {
|
|
559
773
|
// Simulate email sending and verification
|
|
560
774
|
await Promise.resolve(profile);
|
|
561
775
|
console.log(`Verification email sent to ${profile.email}`);
|
|
@@ -563,9 +777,16 @@ async function sendVerificationEmail(profile: UserProfile): Promise<Result<UserP
|
|
|
563
777
|
}
|
|
564
778
|
|
|
565
779
|
// Main registration pipeline
|
|
566
|
-
async function registerUser(
|
|
780
|
+
async function registerUser(
|
|
781
|
+
input: UserInput,
|
|
782
|
+
): Promise<Result<UserProfile, string | string[]>> {
|
|
567
783
|
const res = await Result.Ok(input)
|
|
568
|
-
.validate([
|
|
784
|
+
.validate([
|
|
785
|
+
// handles both sync and async functions
|
|
786
|
+
({ email }) => guardEmail(email),
|
|
787
|
+
({ email }) => guardEmailAvailability(email),
|
|
788
|
+
({ password }) => guardPassword(password),
|
|
789
|
+
])
|
|
569
790
|
.flatMap(createUserProfile)
|
|
570
791
|
.flatMap(sendVerificationEmail)
|
|
571
792
|
.toPromise();
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region rolldown:runtime
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
|
|
25
|
+
Object.defineProperty(exports, '__toESM', {
|
|
26
|
+
enumerable: true,
|
|
27
|
+
get: function () {
|
|
28
|
+
return __toESM;
|
|
29
|
+
}
|
|
30
|
+
});
|