@carbonteq/fp 0.7.0 → 0.8.0-alpha.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 +585 -12
- package/package.json +16 -16
- package/dist/chunk-7QVYU63E.js +0 -7
- package/dist/chunk-7QVYU63E.js.map +0 -1
- package/dist/index.cjs +0 -46
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -4
- package/dist/index.d.ts +0 -4
- package/dist/index.js +0 -16
- package/dist/index.js.map +0 -1
- package/dist/match.cjs +0 -43
- package/dist/match.cjs.map +0 -1
- package/dist/match.d.cts +0 -14
- package/dist/match.d.ts +0 -14
- package/dist/match.js +0 -20
- package/dist/match.js.map +0 -1
- package/dist/option.cjs +0 -227
- package/dist/option.cjs.map +0 -1
- package/dist/option.d.cts +0 -58
- package/dist/option.d.ts +0 -58
- package/dist/option.js +0 -204
- package/dist/option.js.map +0 -1
- package/dist/result.cjs +0 -288
- package/dist/result.cjs.map +0 -1
- package/dist/result.d.cts +0 -150
- package/dist/result.d.ts +0 -150
- package/dist/result.js +0 -264
- package/dist/result.js.map +0 -1
- package/dist/tuple.cjs +0 -41
- package/dist/tuple.cjs.map +0 -1
- package/dist/tuple.d.cts +0 -9
- package/dist/tuple.d.ts +0 -9
- package/dist/tuple.js +0 -18
- package/dist/tuple.js.map +0 -1
- package/dist/unit.cjs +0 -29
- package/dist/unit.cjs.map +0 -1
- package/dist/unit.d.cts +0 -4
- package/dist/unit.d.ts +0 -4
- package/dist/unit.js +0 -6
- package/dist/unit.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Carbonteq Functional Programming Utilities (fp)
|
|
2
|
+
|
|
3
|
+
## Description
|
|
4
|
+
|
|
5
|
+
`fp` is a lightweight TypeScript library designed to simplify functional programming by providing essential types like `Option` and `Result`. It helps developers handle errors, manage optional values, and write expressive, composable code.
|
|
2
6
|
|
|
3
7
|
## Installation
|
|
4
8
|
|
|
@@ -14,24 +18,593 @@ pnpm i @carbonteq/fp
|
|
|
14
18
|
yarn add @carbonteq/fp
|
|
15
19
|
```
|
|
16
20
|
|
|
17
|
-
|
|
21
|
+
```sh
|
|
22
|
+
bun add @carbonteq/fp
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
# But why fp?
|
|
26
|
+
|
|
27
|
+
In JavaScript and TypeScript, dealing with `null`, `undefined`, and errors can lead to verbose, error-prone code. `fp` introduces functional paradigms that make handling these cases cleaner and more reliable. By leveraging `fp`, you can reduce boilerplate, improve readability, and create more maintainable applications.
|
|
28
|
+
|
|
29
|
+
To demonstrate the utility of `fp`, let us consider a use case where we need to retrieve a user's email and address.
|
|
30
|
+
|
|
31
|
+
### Without using the `fp` library
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
function getUserByEmail(user: { email?: string }): string | null {
|
|
35
|
+
return user.email ? user.email : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function getUserAdress(user: { email?: string }): string | null {
|
|
39
|
+
return user.email ? "Some Address" : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const email = getUserByEmail({ email: "test@test.com" });
|
|
43
|
+
if (email) {
|
|
44
|
+
const address = getUserAdress(email);
|
|
45
|
+
if (address) {
|
|
46
|
+
console.log(`User ${email} has address: ${address}`);
|
|
47
|
+
} else {
|
|
48
|
+
console.error("Address not found");
|
|
49
|
+
}
|
|
50
|
+
} else {
|
|
51
|
+
console.error("Email not found");
|
|
52
|
+
}
|
|
53
|
+
// Output: User test@test.com has address: Some Address
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Now imagine if we had more complex use cases that involved more than two optional values. We would have to nest if statements and handle errors manually. This is where `fp` comes in.
|
|
57
|
+
|
|
58
|
+
### With using the `fp` library
|
|
18
59
|
|
|
19
60
|
```typescript
|
|
20
61
|
import { Option, matchOpt } from "@carbonteq/fp";
|
|
21
62
|
|
|
22
|
-
|
|
23
|
-
|
|
63
|
+
function getUserByEmail(user: { email?: string }): Option<string> {
|
|
64
|
+
return user.email ? Option.Some(user.email) : Option.None;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function getUserAddress(user: { email?: string }): Option<string> {
|
|
68
|
+
return user.email ? Option.Some("Some Address") : Option.None;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const res = getUserByEmail({ email: "test@test.com" }).flatZip((email) => getUserAddress({ email }));
|
|
72
|
+
|
|
73
|
+
matchOpt(res, {
|
|
74
|
+
Some: (res) => {
|
|
75
|
+
console.log(`User ${res[0]} has address: ${res[1]}`);
|
|
76
|
+
},
|
|
77
|
+
None: () => {
|
|
78
|
+
console.error("User or Address not found");
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
// Output: User test@test.com has address: Some Address
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
# Table of Contents
|
|
85
|
+
|
|
86
|
+
- [Usage](#usage)
|
|
87
|
+
- [The `Result` type](#the-result-type)
|
|
88
|
+
- [The `Option` type](#the-option-type)
|
|
89
|
+
- [Cheatsheet](#cheatsheet)
|
|
90
|
+
- [map](#map)
|
|
91
|
+
- [flatMap](#flatmap)
|
|
92
|
+
- [zip](#zip)
|
|
93
|
+
- [flatZip](#flatzip)
|
|
94
|
+
- [Comparison of map and zip](#comparison-of-map-flatmap-zip-and-flatzip)
|
|
95
|
+
- [Some Other Useful Functions](#some-other-useful-functions)
|
|
96
|
+
- [mapErr](#maperr)
|
|
97
|
+
- [mapOr](#mapor)
|
|
98
|
+
- [tap](#tap)
|
|
99
|
+
- [all](#all)
|
|
100
|
+
- [validate](#validate)
|
|
101
|
+
- [unwrap](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
|
|
102
|
+
- [safeUnwrapErr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
|
|
103
|
+
- [unwrapOr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
|
|
104
|
+
- [unwrapOrElse](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
|
|
105
|
+
- [safeUnwrap](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
|
|
106
|
+
- [unwrapErr](#unwrap-safeunwraperr-unwrapor-unwraporelse-safeunwrap-and-unwraperr)
|
|
107
|
+
- [Build Your First Pipeline](#build-your-first-pipeline)
|
|
108
|
+
- [Synchronous Pipeline](#synchronous-pipeline)
|
|
109
|
+
- [Asynchronous Pipeline](#asynchronous-pipeline)
|
|
110
|
+
|
|
111
|
+
# Usage
|
|
112
|
+
|
|
113
|
+
## The `Result` type
|
|
114
|
+
|
|
115
|
+
`Result` represents a value that can be either a success (`Ok`) or a failure (`Err`). It simplifies error handling by making success and failure explicit.
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import { Result } from "@carbonteq/fp";
|
|
119
|
+
|
|
120
|
+
const res1: Result<number, string> = Result.Ok(5); // Contains the value 5
|
|
121
|
+
const res2: Result<number, string> = Result.Err("Some Error"); // Contains the error "Some Error"
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## The `Option` type
|
|
125
|
+
|
|
126
|
+
The `Option` type represents a value that might or might not be present. It eliminates the need for manual checks for `null` or `undefined`.
|
|
127
|
+
|
|
128
|
+
```typescript
|
|
129
|
+
import { Option } from "@carbonteq/fp";
|
|
130
|
+
|
|
131
|
+
const opt1: Option<number> = Option.Some(5); // Contains the value 5
|
|
132
|
+
const opt2: Option<number> = Option.None; // Contains no value (None)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## Cheatsheet
|
|
138
|
+
|
|
139
|
+
#### `map`
|
|
140
|
+
|
|
141
|
+
Transforms the `Some` or `Ok` value inside `Option` or `Result`.
|
|
142
|
+
|
|
143
|
+
Let's say we want to apply a 10% bonus to the account balance of a user.
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
import { Option } from "@carbonteq/fp";
|
|
24
147
|
|
|
25
|
-
|
|
148
|
+
async function fetchUserBalanceFromDatabase(userId: string): Promise<Option<number>> {
|
|
149
|
+
// Simulate fetching balance from a database
|
|
150
|
+
await Promise.resolve(userId);
|
|
151
|
+
return Option.Some(100);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function applyBonus() {
|
|
155
|
+
const userId = "user123"; // Example user ID
|
|
156
|
+
const balanceOption = await Option.Some(userId)
|
|
157
|
+
.flatMap(fetchUserBalanceFromDatabase)
|
|
158
|
+
.map((balance) => balance * 1.1)
|
|
159
|
+
.toPromise(); // Apply a 10% bonus if balance exists
|
|
160
|
+
return balanceOption;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
console.log(await applyBonus()); // Output: Some(110)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
#### `flatMap`
|
|
167
|
+
|
|
168
|
+
`flatMap` is used to chain operations where each step returns an `Option` or `Result`. It avoids nested structures like `Option<Option<T>>` or `Result<Result<T, E>, E>` by "flattening" them into a single level.
|
|
169
|
+
|
|
170
|
+
Let's say we want to validate user input and then save it to a database:
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
import { Result } from "@carbonteq/fp";
|
|
174
|
+
|
|
175
|
+
// Function to validate user input
|
|
176
|
+
const validateUserData = (name: string, age: number): Result<{ name: string; age: number }, Error> => {
|
|
177
|
+
if (name.trim() === "") {
|
|
178
|
+
return Result.Err(new Error("Name cannot be empty"));
|
|
179
|
+
}
|
|
180
|
+
if (age < 0 || age > 120) {
|
|
181
|
+
return Result.Err(new Error("Age must be between 0 and 120"));
|
|
182
|
+
}
|
|
183
|
+
return Result.Ok({ name, age });
|
|
26
184
|
};
|
|
27
185
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
});
|
|
186
|
+
// Simulated asynchronous task to save user data to a "database"
|
|
187
|
+
const saveUserData = async (user: { name: string; age: number }): Promise<Result<string, Error>> => {
|
|
188
|
+
// Simulate saving to database
|
|
189
|
+
await Promise.resolve(user);
|
|
190
|
+
return Result.Ok(`User ${user.name} saved successfully!`);
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// Chaining validation and save using `flatMap`
|
|
194
|
+
const processUser = async (name: string, age: number): Promise<Result<string, Error>> => {
|
|
195
|
+
const validationResult = await validateUserData(name, age).flatMap(saveUserData).toPromise();
|
|
196
|
+
return validationResult;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
console.log(await processUser("Alice", 30)); // Output: Result.Ok("User Alice saved successfully!")
|
|
200
|
+
|
|
201
|
+
/* validationResult is of type Result<string, Error> instead of Result<Result<string, Error>, Error> (which is what would have happened if we used map instead of flatMap) */
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
#### `zip`
|
|
205
|
+
|
|
206
|
+
Creates a tuple `[T, U]` where the second value `U` is _derived_ from the first value `T` using a function `f`.
|
|
207
|
+
For example, suppose we want to pair the product's original price `T` and discounted price `U`.
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
import { Result } from "@carbonteq/fp";
|
|
211
|
+
|
|
212
|
+
async function fetchProductPrice(productId: string): Promise<Result<number, Error>> {
|
|
213
|
+
// Simulate fetching price from a database
|
|
214
|
+
await Promise.resolve(productId);
|
|
215
|
+
return Result.Ok(100);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function applyDiscount(productId: string): Promise<Result<[number, number], Error>> {
|
|
219
|
+
const originalPrice = await Result.Ok(productId)
|
|
220
|
+
.flatMap(fetchProductPrice)
|
|
221
|
+
.zip((price) => price * 0.9)
|
|
222
|
+
.toPromise();
|
|
223
|
+
return originalPrice; //originalPrice is of type Result<[number, number], Error>
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
console.log(await applyDiscount("123")); // Output: Result.Ok([100, 90])
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Here `derivedPair` is a `Result<[number, number], Error>`. Note that `T` = `100` and `U` = `90`.
|
|
230
|
+
|
|
231
|
+
#### `flatZip`
|
|
232
|
+
|
|
233
|
+
Combines the current `Result<T, E>` with another `Result<U, E2>`, or the current `Option<T>` with another `Option<U>`. Unlike zip, which pairs a value with a derived one, flatZip works with **two independent Result/Option values** and combines their contents into a tuple `[T, U]`. It ensures the Result/Option values are Ok/Some to proceed; otherwise, it propagates the first encountered Err/None.
|
|
234
|
+
|
|
235
|
+
Lets say we want to combine the product price and product stock into a tuple `[number, number]`.
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
import { Option } from "@carbonteq/fp";
|
|
239
|
+
|
|
240
|
+
// Simulated function to fetch product price
|
|
241
|
+
async function fetchProductPrice(productId: string): Promise<Option<number>> {
|
|
242
|
+
// Simulate fetching price from a database
|
|
243
|
+
await Promise.resolve(productId);
|
|
244
|
+
return Option.Some(100);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Simulated function to fetch product stock
|
|
248
|
+
async function fetchProductStock(productId: string): Promise<Option<number>> {
|
|
249
|
+
// Simulate fetching stock from a database
|
|
250
|
+
await Promise.resolve(productId);
|
|
251
|
+
return Option.Some(50);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Function to combine price and stock using flatZip
|
|
255
|
+
async function fetchProductDetails(productId: string): Promise<Option<[number, number]>> {
|
|
256
|
+
const productDetails = await Option.Some(productId).flatMap(fetchProductPrice).flatZip(fetchProductStock).toPromise();
|
|
257
|
+
return productDetails; // Option<[number, number]>
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
console.log(await fetchProductDetails("123")); // Output: Option.Some([100, 50])
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Comparison of `map`, `flatMap`, `zip`, and `flatZip`
|
|
264
|
+
|
|
265
|
+
| **Method** | **`map`** | **`flatMap`** | **`zip`** | **`flatZip`** | |
|
|
266
|
+
| --------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | --- |
|
|
267
|
+
| **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
|
+
| **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
|
+
| **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]>`. |
|
|
270
|
+
| **Error Propagation** | Propagates `Err`/`None` if the `Result`/`Option` is `Err`/`None`. | Propagates the first `Err`/`None` encountered in the chain. | Propagates `Err`/`None` if the current `Result`/`Option` or derived value is `Err`/`None`. | Propagates the first `Err`/`None` encountered between the two `Result`/`Option` values. |
|
|
271
|
+
| **Use Case** | When you want to transform a value inside `Ok`/`Some`. | When the next computation depends on the current value and returns a `Result`/`Option`. | When you want to pair the current value with a derived one. | When you want to combine two independent `Result`/`Option` values into a tuple. |
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
### Some Other Useful Functions
|
|
276
|
+
|
|
277
|
+
#### `mapErr`
|
|
278
|
+
|
|
279
|
+
Transforms the `Err` value inside `Result`.
|
|
280
|
+
|
|
281
|
+
```typescript
|
|
282
|
+
import { Result } from "@carbonteq/fp";
|
|
283
|
+
|
|
284
|
+
// Simulated function to divide two numbers
|
|
285
|
+
function divideNumbers(a: number, b: number): Result<number, Error> {
|
|
286
|
+
if (b === 0) {
|
|
287
|
+
return Result.Err(new Error("Division by zero"));
|
|
288
|
+
}
|
|
289
|
+
return Result.Ok(a / b);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// 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
|
+
function safeDivide(a: number, b: number): Result<number, string> {
|
|
294
|
+
const res = divideNumbers(a, b).mapErr((err) => `Operation failed: ${err.message}`);
|
|
295
|
+
return res;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Example usage
|
|
299
|
+
console.log(safeDivide(10, 2)); // Result.Ok(5)
|
|
300
|
+
console.log(safeDivide(10, 0)); // Result.Err("Operation failed: Division by zero")
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
#### `mapOr`
|
|
304
|
+
|
|
305
|
+
Checks if the `Option` or `Result` is `Some` or `Ok`, and if so, applies the function to the value inside. If the `Option` or `Result` is `None` or `Err`, it returns the default value.
|
|
306
|
+
|
|
307
|
+
```typescript
|
|
308
|
+
import { Option } from "@carbonteq/fp";
|
|
309
|
+
|
|
310
|
+
// Simulated function to find a user by id
|
|
311
|
+
async function findUserById(id: number): Promise<Option<number>> {
|
|
312
|
+
// Simulate a database call that either returns a user or null
|
|
313
|
+
await Promise.resolve(id);
|
|
314
|
+
if (id === 0) {
|
|
315
|
+
return Option.None;
|
|
316
|
+
}
|
|
317
|
+
return Option.Some(id);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// A safe function that returns a string error message if the user is not found, instead of throwing an exception
|
|
321
|
+
async function safeFindUserById(id: number): Promise<Option<string>> {
|
|
322
|
+
const res = (await findUserById(id)).mapOr(`User not found`, (res) => `User: ${res}`);
|
|
323
|
+
return res;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// Example usage
|
|
327
|
+
console.log(await safeFindUserById(10)); // Some(User: 10)
|
|
328
|
+
console.log(await safeFindUserById(0)); // Some(User not found)
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
#### `tap`
|
|
332
|
+
|
|
333
|
+
`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
|
+
|
|
335
|
+
```typescript
|
|
336
|
+
import { Result } from "@carbonteq/fp";
|
|
337
|
+
|
|
338
|
+
// Simulated database functions
|
|
339
|
+
async function findUserById(userId: number): Promise<Result<Record<string, number>, string>> {
|
|
340
|
+
// Simulate a database lookup
|
|
341
|
+
await Promise.resolve(userId);
|
|
342
|
+
if (userId === 0) {
|
|
343
|
+
return Result.Err("User not found");
|
|
344
|
+
}
|
|
345
|
+
return Result.Ok({ id: userId, balance: 100 });
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function updateBalance(user: Record<string, number>, amount: number): Result<Record<string, number>, string> {
|
|
349
|
+
if (user.balance < amount) {
|
|
350
|
+
return Result.Err("Insufficient funds");
|
|
351
|
+
}
|
|
352
|
+
return Result.Ok({ ...user, balance: user.balance - amount });
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Process withdrawal with logging
|
|
356
|
+
const res = (await findUserById(1))
|
|
357
|
+
.tap((user) => console.log(`[Audit] User found: ${user.id}`))
|
|
358
|
+
.flatMap((user) => updateBalance(user, 10))
|
|
359
|
+
.tap((updated) => console.log(`[Transaction] New balance: $${updated.balance}`))
|
|
360
|
+
.mapErr((error) => console.error(`[Alert] Transaction failed: ${error}`));
|
|
361
|
+
|
|
362
|
+
console.log(res); // Result.Ok({ id: 1, balance: 90 })
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
#### `all`
|
|
366
|
+
|
|
367
|
+
`all` is used to combine an array of Results. If any errors exist they are accumulated, else the values are accumulated.
|
|
368
|
+
|
|
369
|
+
```typescript
|
|
370
|
+
const combinedOk = Result.all(Result.Ok(1), Result.Ok(2), Result.Ok(3), Result.Ok(4));
|
|
371
|
+
console.log(combinedOk.unwrap()); // [1, 2, 3, 4]
|
|
372
|
+
const combinedErr = Result.all(Result.Err(1), Result.Err(2), Result.Err(3), Result.Err(4));
|
|
373
|
+
console.log(combinedErr.unwrapErr()); // [1, 2, 3, 4]
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
#### `validate`
|
|
377
|
+
|
|
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.
|
|
379
|
+
|
|
380
|
+
```typescript
|
|
381
|
+
import { Result } from "@carbonteq/fp";
|
|
382
|
+
|
|
383
|
+
function isPositive(n: number) {
|
|
384
|
+
return n < 0 ? Result.Err(new Error("Input is negative")) : Result.Ok(true);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function isEven(n: number) {
|
|
388
|
+
return n % 2 !== 0 ? Result.Err(new Error("Input is odd")) : Result.Ok(true);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const validatedOk = Result.Ok(2).validate([isPositive, isEven]);
|
|
392
|
+
console.log(validatedOk.unwrap()); // 2
|
|
393
|
+
const validatedErr = Result.Ok(-3).validate([isPositive, isEven]);
|
|
394
|
+
console.log(validatedErr.unwrapErr()); // [Error("Input is negative"), Error("Input is odd")]
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
#### `unwrap`, `safeUnwrapErr`, `unwrapOr`, `unwrapOrElse`, `safeUnwrap`, and `unwrapErr`
|
|
398
|
+
|
|
399
|
+
These functions are used to extract the value from a `Result`. Note that **only `unwrap` and `safeUnwrap` are available for `Option`**.
|
|
400
|
+
|
|
401
|
+
```typescript
|
|
402
|
+
import { Result } from "@carbonteq/fp";
|
|
403
|
+
|
|
404
|
+
function divideNumbers(a: number, b: number): Result<number, Error> {
|
|
405
|
+
if (b === 0) {
|
|
406
|
+
return Result.Err(new Error("Division by zero"));
|
|
407
|
+
}
|
|
408
|
+
return Result.Ok(a / b);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Example usage of each function
|
|
412
|
+
let result = divideNumbers(10, 2);
|
|
413
|
+
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
|
+
|
|
416
|
+
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
|
+
console.log(result.safeUnwrap()); // safeUnwrap: null (Safely unwraps the value, returning null if it's an Err instead of throwing an error.)
|
|
420
|
+
|
|
421
|
+
const errorResult = Result.Err(new Error("Something went wrong"));
|
|
422
|
+
console.log(errorResult.unwrapErr()); // unwrapErr: Error: Something went wrong (Extracts the error from Result.Err, throwing an error if it's Ok)
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
## Build Your First Pipeline
|
|
426
|
+
|
|
427
|
+
Let's build a pipeline for processing an e-commerce order. This example demonstrates handling user input validation, inventory checks, and order processing.
|
|
428
|
+
|
|
429
|
+
#### Synchronous Pipeline
|
|
430
|
+
|
|
431
|
+
```typescript
|
|
432
|
+
import { Result, matchRes } from "@carbonteq/fp";
|
|
433
|
+
|
|
434
|
+
interface Order {
|
|
435
|
+
productId: string;
|
|
436
|
+
quantity: number;
|
|
437
|
+
userId: string;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
interface ProcessedOrder {
|
|
441
|
+
orderId: string;
|
|
442
|
+
total: number;
|
|
443
|
+
status: "confirmed" | "failed";
|
|
444
|
+
order: Order;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// Validate order input
|
|
448
|
+
function guardOrder(order: Order): Result<Order, string> {
|
|
449
|
+
if (!order.productId) return Result.Err("Product ID is required");
|
|
450
|
+
if (order.quantity <= 0) return Result.Err("Quantity must be positive");
|
|
451
|
+
if (!order.userId) return Result.Err("User ID is required");
|
|
452
|
+
return Result.Ok(order);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// Check product availability
|
|
456
|
+
function guardInventoryCheck(order: Order): Result<Order, string> {
|
|
457
|
+
const availableStock = 100; // Simulated stock
|
|
458
|
+
return order.quantity <= availableStock ? Result.Ok(order) : Result.Err(`Insufficient stock. Available: ${availableStock}`);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Calculate order total
|
|
462
|
+
function calculateTotal(order: Order): Result<number, string> {
|
|
463
|
+
const price = 29.99; // Simulated price
|
|
464
|
+
return Result.Ok(order.quantity * price);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Process the order
|
|
468
|
+
function processOrder(order: Order): Result<ProcessedOrder, string> {
|
|
469
|
+
return Result.Ok(order)
|
|
470
|
+
.validate([guardOrder, guardInventoryCheck])
|
|
471
|
+
.flatZip(calculateTotal)
|
|
472
|
+
.map(([order, total]) => ({
|
|
473
|
+
orderId: `ORD-${Date.now()}`,
|
|
474
|
+
total: total,
|
|
475
|
+
status: "confirmed" as const,
|
|
476
|
+
order: order,
|
|
477
|
+
}))
|
|
478
|
+
.mapErr((error) => `Order processing failed: ${error}`);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// Usage
|
|
482
|
+
const order: Order = {
|
|
483
|
+
productId: "PROD-123",
|
|
484
|
+
quantity: 2,
|
|
485
|
+
userId: "USER-456",
|
|
33
486
|
};
|
|
34
487
|
|
|
35
|
-
|
|
36
|
-
|
|
488
|
+
const result = processOrder(order);
|
|
489
|
+
|
|
490
|
+
matchRes(result, {
|
|
491
|
+
Ok: (processedOrder) => {
|
|
492
|
+
console.log(`Order confirmed! Order ID: ${processedOrder.orderId}`);
|
|
493
|
+
console.log(`Total: $${processedOrder.total.toFixed(2)}`);
|
|
494
|
+
console.log(`Order: ${JSON.stringify(processedOrder.order)}`);
|
|
495
|
+
},
|
|
496
|
+
Err: (error) => {
|
|
497
|
+
console.error(`Error: ${error}`);
|
|
498
|
+
},
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
// Output:
|
|
502
|
+
// Order confirmed! Order ID: ORD-1716888600000
|
|
503
|
+
// Total: $59.98
|
|
504
|
+
// Order: {"productId":"PROD-123","quantity":2,"userId":"USER-456"}
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
#### Asynchronous Pipeline
|
|
508
|
+
|
|
509
|
+
Let's build an asynchronous pipeline for a user registration system that includes credentials verification and profile setup.
|
|
510
|
+
|
|
511
|
+
```typescript
|
|
512
|
+
import { Result, matchRes } from "@carbonteq/fp";
|
|
513
|
+
|
|
514
|
+
interface UserInput {
|
|
515
|
+
email: string;
|
|
516
|
+
password: string;
|
|
517
|
+
name: string;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
interface UserProfile {
|
|
521
|
+
userId: string;
|
|
522
|
+
email: string;
|
|
523
|
+
name: string;
|
|
524
|
+
verificationStatus: "pending" | "verified";
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Validate email format
|
|
528
|
+
async function guardEmail(email: string): Promise<Result<string, string>> {
|
|
529
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
530
|
+
return emailRegex.test(email) ? Result.Ok(email) : Result.Err("Invalid email format");
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// Check if email is already registered
|
|
534
|
+
async function guardEmailAvailability(email: string): Promise<Result<string, string>> {
|
|
535
|
+
// Simulate database check
|
|
536
|
+
await Promise.resolve(email);
|
|
537
|
+
const registeredEmails = ["existing@example.com"];
|
|
538
|
+
return !registeredEmails.includes(email) ? Result.Ok(email) : Result.Err("Email already registered");
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// Validate password strength
|
|
542
|
+
async function guardPassword(password: string): Promise<Result<string, string>> {
|
|
543
|
+
return password.length >= 8 ? Result.Ok(password) : Result.Err("Password must be at least 8 characters");
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Create user profile
|
|
547
|
+
async function createUserProfile(input: UserInput): Promise<Result<UserProfile, string>> {
|
|
548
|
+
const userProfile: UserProfile = {
|
|
549
|
+
userId: `USER-${Date.now()}`,
|
|
550
|
+
email: input.email,
|
|
551
|
+
name: input.name,
|
|
552
|
+
verificationStatus: "pending",
|
|
553
|
+
};
|
|
554
|
+
return Result.Ok(userProfile);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// Send verification email
|
|
558
|
+
async function sendVerificationEmail(profile: UserProfile): Promise<Result<UserProfile, string>> {
|
|
559
|
+
// Simulate email sending and verification
|
|
560
|
+
await Promise.resolve(profile);
|
|
561
|
+
console.log(`Verification email sent to ${profile.email}`);
|
|
562
|
+
return Result.Ok(profile);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// Main registration pipeline
|
|
566
|
+
async function registerUser(input: UserInput): Promise<Result<UserProfile, string | string[]>> {
|
|
567
|
+
const res = await Result.Ok(input)
|
|
568
|
+
.validate([({ email }) => guardEmail(email), ({ email }) => guardEmailAvailability(email), ({ password }) => guardPassword(password)])
|
|
569
|
+
.flatMap(createUserProfile)
|
|
570
|
+
.flatMap(sendVerificationEmail)
|
|
571
|
+
.toPromise();
|
|
572
|
+
|
|
573
|
+
return res;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// Usage
|
|
577
|
+
async function main() {
|
|
578
|
+
const userInput: UserInput = {
|
|
579
|
+
email: "newuser@example.com",
|
|
580
|
+
password: "securepass123",
|
|
581
|
+
name: "John Doe",
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
const result = await registerUser(userInput);
|
|
585
|
+
|
|
586
|
+
matchRes(result, {
|
|
587
|
+
Ok: (profile) => {
|
|
588
|
+
console.log(`Email: ${profile.email}`);
|
|
589
|
+
console.log("Registration successful!");
|
|
590
|
+
console.log(`User ID: ${profile.userId}`);
|
|
591
|
+
console.log(`Verification Status: ${profile.verificationStatus}`);
|
|
592
|
+
},
|
|
593
|
+
Err: (error) => {
|
|
594
|
+
console.error(`Registration failed: ${error}`);
|
|
595
|
+
},
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
main();
|
|
600
|
+
// Output:
|
|
601
|
+
// Verification email sent to newuser@example.com
|
|
602
|
+
// Email: newuser@example.com
|
|
603
|
+
// Registration successful!
|
|
604
|
+
// User ID: USER-1737921964102
|
|
605
|
+
// Verification Status: pending
|
|
37
606
|
```
|
|
607
|
+
|
|
608
|
+
## Contributing
|
|
609
|
+
|
|
610
|
+
Contributions are welcome! Feel free to open issues or submit pull requests.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@carbonteq/fp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0-alpha.0",
|
|
4
4
|
"description": "FP utils",
|
|
5
5
|
"author": "Arslan <rslnkrmt2552@gmail.com>",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -32,19 +32,6 @@
|
|
|
32
32
|
"access": "public",
|
|
33
33
|
"registry": "https://registry.npmjs.org/"
|
|
34
34
|
},
|
|
35
|
-
"scripts": {
|
|
36
|
-
"lint": "biome check src tests",
|
|
37
|
-
"lint:fix": "biome check src tests --write --unsafe",
|
|
38
|
-
"fmt:dry": "biome format src tests",
|
|
39
|
-
"fmt": "biome format src tests --write",
|
|
40
|
-
"tc": "tsc --pretty --noEmit --project tsconfig.build.json",
|
|
41
|
-
"build": "tsup",
|
|
42
|
-
"dev": "tsup --watch",
|
|
43
|
-
"test": "tsx --test tests/*.test.ts",
|
|
44
|
-
"test:dbg": "tsx --inspect-brk --test tests/*.test.ts",
|
|
45
|
-
"release": "changeset publish",
|
|
46
|
-
"tag": "changeset tag"
|
|
47
|
-
},
|
|
48
35
|
"devDependencies": {
|
|
49
36
|
"@biomejs/biome": "^1.8.3",
|
|
50
37
|
"@changesets/cli": "^2.27.7",
|
|
@@ -63,5 +50,18 @@
|
|
|
63
50
|
"npm": ">=8.0.0",
|
|
64
51
|
"yarn": ">=1.22.0"
|
|
65
52
|
},
|
|
66
|
-
"
|
|
67
|
-
|
|
53
|
+
"scripts": {
|
|
54
|
+
"lint": "biome check src tests",
|
|
55
|
+
"lint:fix": "biome check src tests --write --unsafe",
|
|
56
|
+
"fmt:dry": "biome format src tests",
|
|
57
|
+
"fmt": "biome format src tests --write",
|
|
58
|
+
"tc": "tsc --pretty --noEmit --project tsconfig.build.json",
|
|
59
|
+
"build": "NODE_ENV=production tsup",
|
|
60
|
+
"bd": "tsup",
|
|
61
|
+
"dev": "tsup --watch",
|
|
62
|
+
"test": "tsx --test tests/*.test.ts",
|
|
63
|
+
"test:dbg": "tsx --inspect-brk --test tests/*.test.ts",
|
|
64
|
+
"release": "changeset publish",
|
|
65
|
+
"tag": "changeset tag"
|
|
66
|
+
}
|
|
67
|
+
}
|
package/dist/chunk-7QVYU63E.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|