ok-fp 0.0.1 → 0.2.1

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 CHANGED
@@ -1,19 +1,19 @@
1
- # OKFP
1
+ # OK-FP
2
2
 
3
- ![npm (scoped)](https://img.shields.io/npm/v/okfp?color=orange&label=npm) ![license](https://img.shields.io/badge/license-MIT-blue)
3
+ ![npm (scoped)](https://img.shields.io/npm/v/ok-fp?color=orange&label=npm) ![license](https://img.shields.io/badge/license-MIT-blue)
4
4
 
5
- > Essential typed effects for TypeScript.
5
+ > Essential Effect Data Types for TypeScript
6
6
 
7
- OKFP is a small, focused functional programming toolkit for TypeScript.
7
+ OK-FP is a small, focused functional programming toolkit for TypeScript.
8
8
 
9
9
  It provides a minimal set of **typed effects**: composable, type-safe wrappers for optional values, errors, and async computations.
10
10
 
11
11
  ## Status
12
12
 
13
- OKFP is pre-1.0.
13
+ OK-FP is pre-1.0.
14
14
 
15
- - ✅ Implemented: `Option`, `Either`
16
- - 🚧 Planned before `v1.0.0`: `Validation`, `Task`, `TaskEither`
15
+ - ✅ Implemented: `Option`, `Either`, `Validation`, `Task`
16
+ - 🚧 Planned before `v1.0.0`: `TaskEither`
17
17
 
18
18
  See: [ROADMAP.md](./ROADMAP.md)
19
19
 
@@ -22,10 +22,10 @@ See: [ROADMAP.md](./ROADMAP.md)
22
22
  Install with your package manager of choice:
23
23
 
24
24
  ```bash
25
- npm install okfp
25
+ npm install ok-fp
26
26
  # or
27
- # pnpm add okfp
28
- # yarn add okfp
27
+ # pnpm add ok-fp
28
+ # yarn add ok-fp
29
29
  ```
30
30
 
31
31
  ### Basic example
@@ -33,7 +33,7 @@ npm install okfp
33
33
  This example shows a small pipeline using `Option`.
34
34
 
35
35
  ```ts
36
- import { type Option, some, none } from "okfp/option";
36
+ import { type Option, some, none } from "ok-fp/option";
37
37
 
38
38
  const parseNumber = (input: string): Option<number> => {
39
39
  const n = Number(input);
@@ -44,27 +44,25 @@ const nonZero = (n: number): Option<number> => (n !== 0 ? some(n) : none());
44
44
 
45
45
  const positive = (n: number): Option<number> => (n > 0 ? some(n) : none());
46
46
 
47
- const reciprocal = (n: number): Option<number> => some(1 / n);
48
-
49
47
  const compute = (input: string): Option<number> =>
50
48
  parseNumber(input)
51
- .flatMap(positive) // must be > 0
52
- .flatMap(nonZero) // must not be 0
53
- .flatMap(reciprocal) // compute 1 / n
54
- .map((n) => n * 100); // scale result
49
+ .flatMap(nonZero) // must not be 0
50
+ .flatMap(positive) // must be > 0
51
+ .map((n) => 1 / n) // reciprocal (no need for flatMap)
52
+ .map((n) => n * 100); // scale
55
53
 
56
54
  // Usage (returns Option instances)
57
- compute("4"); // returns Option.some(25)
58
- compute("0"); // returns Option.none() (fails nonZero)
59
- compute("-3"); // returns Option.none() (fails positive)
60
- compute("abc"); // returns Option.none() (fails parsing)
55
+ compute("4"); // returns some(25)
56
+ compute("0"); // returns none() (fails nonZero)
57
+ compute("-3"); // returns none() (fails positive)
58
+ compute("abc"); // returns none() (fails parsing)
61
59
  ```
62
60
 
63
61
  ## Documentation
64
62
 
65
63
  Full documentation and API reference are available in the docs site or the `docs/` folder.
66
64
 
67
- [API docs](https://pwlmc.github.io/okfp/)
65
+ [API docs](https://pwlmc.github.io/ok-fp/)
68
66
 
69
67
  ## License
70
68
 
package/dist/either.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as fromOption, c as tryCatch, d as Left, f as Right, i as fromNullable, l as Either, n as map3, o as left, r as sequence, s as right, t as map2, u as EitherV } from "./helpers-BGxhvbJN.mjs";
2
- export { type Either, EitherV, Left, Right, fromNullable, fromOption, left, map2, map3, right, sequence, tryCatch };
1
+ import { a as fromOption, c as tryCatch, d as EitherValue, f as Left, i as fromNullable, l as Either, n as map3, o as left, p as Right, r as sequence, s as right, t as map2, u as EitherResult } from "./helpers-qdt9BxJz.mjs";
2
+ export { type Either, EitherResult, EitherValue, Left, Right, fromNullable, fromOption, left, map2, map3, right, sequence, tryCatch };
@@ -3,7 +3,7 @@ type Some<T> = {
3
3
  some: T;
4
4
  };
5
5
  type None = symbol;
6
- type OptionV<T> = Some<T> | None;
6
+ type OptionValue<T> = Some<T> | None;
7
7
  declare const NONE: unique symbol;
8
8
  //#endregion
9
9
  //#region src/option/option.d.ts
@@ -321,16 +321,16 @@ type Left<E> = {
321
321
  type Right<T> = {
322
322
  readonly right: T;
323
323
  };
324
- type EitherV<E, T> = Left<E> | Right<T>;
325
- //#endregion
326
- //#region src/either/either.d.ts
327
- type Result<E, T> = {
324
+ type EitherValue<E, T> = Left<E> | Right<T>;
325
+ type EitherResult<E, T> = {
328
326
  ok: true;
329
327
  value: T;
330
328
  } | {
331
329
  ok: false;
332
330
  error: E;
333
331
  };
332
+ //#endregion
333
+ //#region src/either/either.d.ts
334
334
  type Either<E, T> = {
335
335
  /**
336
336
  * Filters the Either based on a predicate function applied to the Right value.
@@ -523,7 +523,7 @@ type Either<E, T> = {
523
523
  * console.log(errorResult.error); // "error"
524
524
  * ```
525
525
  */
526
- toResult: () => Result<E, T>;
526
+ toResult: () => EitherResult<E, T>;
527
527
  };
528
528
  //#endregion
529
529
  //#region src/either/constructors.d.ts
@@ -662,4 +662,4 @@ declare function map3<EA, A, EB, B, EC, C, D>(eitherA: Either<EA, A>, eitherB: E
662
662
  */
663
663
  declare function sequence<E, T>(eithers: Either<E, T>[]): Either<E, T[]>;
664
664
  //#endregion
665
- export { OptionV as C, None as S, fromNullable$1 as _, fromOption as a, Option as b, tryCatch as c, Left as d, Right as f, fromEither as g, sequence$1 as h, fromNullable as i, Either as l, map3$1 as m, map3 as n, left as o, map2$1 as p, sequence as r, right as s, map2 as t, EitherV as u, none as v, Some as w, NONE as x, some as y };
665
+ export { None as C, NONE as S, Some as T, fromEither as _, fromOption as a, some as b, tryCatch as c, EitherValue as d, Left as f, sequence$1 as g, map3$1 as h, fromNullable as i, Either as l, map2$1 as m, map3 as n, left as o, Right as p, sequence as r, right as s, map2 as t, EitherResult as u, fromNullable$1 as v, OptionValue as w, Option as x, none as y };
package/dist/option.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as OptionV, S as None, _ as fromNullable, b as Option, g as fromEither, h as sequence, m as map3, p as map2, v as none, w as Some, x as NONE, y as some } from "./helpers-BGxhvbJN.mjs";
2
- export { NONE, None, type Option, OptionV, Some, fromEither, fromNullable, map2, map3, none, sequence, some };
1
+ import { C as None, S as NONE, T as Some, _ as fromEither, b as some, g as sequence, h as map3, m as map2, v as fromNullable, w as OptionValue, x as Option, y as none } from "./helpers-qdt9BxJz.mjs";
2
+ export { NONE, None, type Option, OptionValue, Some, fromEither, fromNullable, map2, map3, none, sequence, some };
package/dist/task.d.mts CHANGED
@@ -1,16 +1,146 @@
1
- //#region src/task.d.ts
2
- type TaskV<T> = () => Promise<T>;
3
- type Task<_T> = {
4
- map: never;
5
- ap: never;
6
- flatMap: never;
7
- tap: never;
8
- run: never;
1
+ //#region src/task/model.d.ts
2
+ type TaskValue<T> = () => Promise<T>;
3
+ //#endregion
4
+ //#region src/task/task.d.ts
5
+ type Task<T> = {
6
+ /**
7
+ * Transforms the value produced by the Task using a mapping function.
8
+ *
9
+ * @typeParam U - The type of the transformed value
10
+ * @param mapper - Function to transform the resolved value
11
+ * @returns A new Task that resolves with the transformed value
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * task(5).map(x => x * 2).run() // Promise<10>
16
+ * ```
17
+ */
18
+ map: <U>(mapper: (value: T) => U) => Task<U>;
19
+ /**
20
+ * Applies a function wrapped in a Task to a value wrapped in a Task.
21
+ * Both Tasks are run concurrently.
22
+ *
23
+ * @typeParam A - The type of the argument value
24
+ * @typeParam U - The type of the function's return value
25
+ * @param arg - Task containing the argument to apply the function to
26
+ * @returns Task containing the function result
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const add = (x: number) => (y: number) => x + y;
31
+ * task(add(5)).ap(task(3)).run() // Promise<8>
32
+ * ```
33
+ */
34
+ ap: <A, U>(this: Task<(a: A) => U>, arg: Task<A>) => Task<U>;
35
+ /**
36
+ * Combines this Task with another Task into a tuple.
37
+ * Both Tasks are run concurrently.
38
+ *
39
+ * @typeParam A - The type of the value in the other Task
40
+ * @param taskA - The Task to combine with this one
41
+ * @returns Task containing a tuple of both values
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * task("Alice").zip(task(30)).run() // Promise<["Alice", 30]>
46
+ * ```
47
+ */
48
+ zip: <A>(taskA: Task<A>) => Task<readonly [T, A]>;
49
+ /**
50
+ * Flattens a nested Task structure by removing one level of nesting.
51
+ *
52
+ * @returns The inner Task result
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * task(task(42)).flatten().run() // Promise<42>
57
+ * ```
58
+ */
59
+ flatten: <U>(this: Task<Task<U>>) => Task<U>;
60
+ /**
61
+ * Chains Task-returning operations together (monadic bind).
62
+ *
63
+ * @typeParam U - The type of the value in the returned Task
64
+ * @param mapper - Function that takes a resolved value and returns a Task
65
+ * @returns The Task returned by mapper
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * task(10).flatMap(x => task(x * 2)).run() // Promise<20>
70
+ * ```
71
+ */
72
+ flatMap: <U>(mapper: (value: T) => Task<U>) => Task<U>;
73
+ /**
74
+ * Performs a side effect with the resolved value, returning the original Task unchanged.
75
+ *
76
+ * @param sideEffect - Function to execute with the resolved value (return value is ignored)
77
+ * @returns The same Task instance unchanged
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * task(42)
82
+ * .tap(value => console.log(`Got value: ${value}`))
83
+ * .run() // Logs: "Got value: 42", resolves to 42
84
+ * ```
85
+ */
86
+ tap: (sideEffect: (value: T) => unknown) => Task<T>;
87
+ /**
88
+ * Executes the Task and returns the resulting Promise.
89
+ *
90
+ * @returns A Promise that resolves with the Task's value
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const result = await task(42).run(); // 42
95
+ * ```
96
+ */
97
+ run: () => Promise<T>;
9
98
  };
10
- declare function task<T>(): Task<T>;
11
- declare function fromPromise<T>(_thunk: () => Promise<T>): void;
12
- declare function all(): void;
13
- declare function traverse(): void;
14
- declare function sequence(): void;
15
99
  //#endregion
16
- export { Task, TaskV, all, fromPromise, sequence, task, traverse };
100
+ //#region src/task/constructors.d.ts
101
+ /**
102
+ * Creates a Task that immediately resolves with the provided value.
103
+ *
104
+ * @typeParam T - The type of the value
105
+ * @param value - The value to wrap in a Task
106
+ * @returns Task that resolves with the given value
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const t = task(42); // Task<number>
111
+ * await t.run(); // 42
112
+ * ```
113
+ */
114
+ declare function task<T>(value: T): Task<T>;
115
+ /**
116
+ * Creates a Task from a lazy Promise-returning thunk.
117
+ * The thunk is not called until `run()` is invoked.
118
+ *
119
+ * @typeParam T - The type of the resolved value
120
+ * @param thunk - A function that returns a Promise
121
+ * @returns Task wrapping the lazy Promise
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * const fetchUser = fromPromise(() => fetch("/api/user").then(r => r.json()));
126
+ * await fetchUser.run(); // fetches the user
127
+ * ```
128
+ */
129
+ declare function fromPromise<T>(thunk: () => Promise<T>): Task<T>;
130
+ //#endregion
131
+ //#region src/task/helpers.d.ts
132
+ /**
133
+ * Runs all Tasks concurrently and collects their results into an array.
134
+ * Equivalent to `Promise.all` for Tasks.
135
+ *
136
+ * @param tasks - Array of Tasks to run concurrently
137
+ * @returns Task that resolves with an array of all results
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * await all([task(1), task(2), task(3)]).run() // [1, 2, 3]
142
+ * ```
143
+ */
144
+ declare function all<T>(tasks: Task<T>[]): Task<T[]>;
145
+ //#endregion
146
+ export { type Task, type TaskValue, all, fromPromise, task };
package/dist/task.mjs CHANGED
@@ -1,19 +1,77 @@
1
- //#region src/task.ts
2
- function task() {
3
- throw new Error("Not implemented");
1
+ //#region src/task/task.ts
2
+ function createTask(thunk) {
3
+ const t = {
4
+ map: (mapper) => createTask(() => thunk().then(mapper)),
5
+ ap: function(arg) {
6
+ return createTask(() => Promise.all([this.run(), arg.run()]).then(([fn, a]) => fn(a)));
7
+ },
8
+ zip: (taskA) => t.map((value) => (a) => [value, a]).ap(taskA),
9
+ flatten: function() {
10
+ return this.flatMap((value) => value);
11
+ },
12
+ flatMap: (mapper) => createTask(() => thunk().then((value) => mapper(value).run())),
13
+ tap: (sideEffect) => createTask(() => thunk().then((value) => {
14
+ sideEffect(value);
15
+ return value;
16
+ })),
17
+ run: () => thunk()
18
+ };
19
+ return t;
4
20
  }
5
- function fromPromise(_thunk) {
6
- throw new Error("Not implemented");
7
- }
8
- function all() {
9
- throw new Error("Not implemented");
21
+
22
+ //#endregion
23
+ //#region src/task/constructors.ts
24
+ /**
25
+ * Creates a Task that immediately resolves with the provided value.
26
+ *
27
+ * @typeParam T - The type of the value
28
+ * @param value - The value to wrap in a Task
29
+ * @returns Task that resolves with the given value
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const t = task(42); // Task<number>
34
+ * await t.run(); // 42
35
+ * ```
36
+ */
37
+ function task(value) {
38
+ return createTask(() => Promise.resolve(value));
10
39
  }
11
- function traverse() {
12
- throw new Error("Not implemented");
40
+ /**
41
+ * Creates a Task from a lazy Promise-returning thunk.
42
+ * The thunk is not called until `run()` is invoked.
43
+ *
44
+ * @typeParam T - The type of the resolved value
45
+ * @param thunk - A function that returns a Promise
46
+ * @returns Task wrapping the lazy Promise
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const fetchUser = fromPromise(() => fetch("/api/user").then(r => r.json()));
51
+ * await fetchUser.run(); // fetches the user
52
+ * ```
53
+ */
54
+ function fromPromise(thunk) {
55
+ return createTask(thunk);
13
56
  }
14
- function sequence() {
15
- throw new Error("Not implemented");
57
+
58
+ //#endregion
59
+ //#region src/task/helpers.ts
60
+ /**
61
+ * Runs all Tasks concurrently and collects their results into an array.
62
+ * Equivalent to `Promise.all` for Tasks.
63
+ *
64
+ * @param tasks - Array of Tasks to run concurrently
65
+ * @returns Task that resolves with an array of all results
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * await all([task(1), task(2), task(3)]).run() // [1, 2, 3]
70
+ * ```
71
+ */
72
+ function all(tasks) {
73
+ return createTask(() => Promise.all(tasks.map((t) => t.run())));
16
74
  }
17
75
 
18
76
  //#endregion
19
- export { all, fromPromise, sequence, task, traverse };
77
+ export { all, fromPromise, task };
@@ -1,16 +1,232 @@
1
- import { l as Either } from "./helpers-BGxhvbJN.mjs";
1
+ import { l as Either, x as Option } from "./helpers-qdt9BxJz.mjs";
2
2
 
3
- //#region src/validation.d.ts
4
- type ValidationV<_E, _T> = object;
5
- type Validation<_E, _T> = {
6
- ap: unknown;
7
- map: unknown;
8
- map3: unknown;
3
+ //#region src/validation/model.d.ts
4
+ type Valid<T> = {
5
+ readonly valid: T;
9
6
  };
10
- declare function valid<T, E = never>(): Validation<E, T>;
11
- declare function invalid<E, T = never>(): Validation<E, T>;
12
- declare function fromEither<E, T>(_either: Either<E, T>): Validation<E, T>;
13
- declare function traverse(): void;
14
- declare function sequence(): void;
7
+ type Invalid<E> = {
8
+ readonly invalid: readonly E[];
9
+ };
10
+ type ValidationValue<E, T> = Valid<T> | Invalid<E>;
11
+ type ValidationResult<E, T> = {
12
+ readonly ok: true;
13
+ readonly value: T;
14
+ } | {
15
+ readonly ok: false;
16
+ readonly errors: readonly E[];
17
+ };
18
+ //#endregion
19
+ //#region src/validation/validation.d.ts
20
+ type Validation<E, T> = {
21
+ /**
22
+ * Filters the Valid value based on a predicate function.
23
+ * If the predicate fails, returns Invalid with the provided error.
24
+ * If this Validation is already Invalid, returns the same Invalid unchanged.
25
+ *
26
+ * @param predicate - Function that tests the valid value
27
+ * @param onInvalid - Function that provides the error value when predicate fails
28
+ * @returns The same Validation if Invalid or predicate passes, otherwise Invalid with the provided error
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * const isPositive = (n: number) => n > 0;
33
+ * valid(5).filterOrElse(isPositive, () => "Must be positive") // Valid(5)
34
+ * valid(-3).filterOrElse(isPositive, () => "Must be positive") // Invalid(["Must be positive"])
35
+ * invalid("error").filterOrElse(isPositive, () => "Must be positive") // Invalid(["error"])
36
+ * ```
37
+ */
38
+ filterOrElse: (predicate: (value: T) => boolean, onInvalid: () => E) => Validation<E, T>;
39
+ /**
40
+ * Transforms the valid value using a mapping function.
41
+ * If this Validation is Invalid, returns the same Invalid unchanged.
42
+ *
43
+ * @param mapper - Function to transform the contained value
44
+ * @returns New Validation containing the transformed value, or the same Invalid
45
+ */
46
+ map: <U>(mapper: (value: T) => U) => Validation<E, U>;
47
+ /**
48
+ * Applies a function wrapped in a Validation to a value wrapped in a Validation.
49
+ * Unlike Either, if both are Invalid, errors are accumulated (concatenated).
50
+ *
51
+ * @param arg - Validation containing the argument to apply the function to
52
+ * @returns Validation containing the result, or accumulated errors if any are Invalid
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const add = (x: number) => (y: number) => x + y;
57
+ * valid(add(5)).ap(valid(3)) // Valid(8)
58
+ * valid(add(5)).ap(invalid("err")) // Invalid(["err"])
59
+ * invalid("e1").ap(invalid("e2")) // Invalid(["e1", "e2"]) ← errors accumulated!
60
+ * ```
61
+ */
62
+ ap: <EE, A, U>(this: Validation<E, (a: A) => U>, arg: Validation<EE, A>) => Validation<E | EE, U>;
63
+ /**
64
+ * Combines this Validation with another Validation into a tuple.
65
+ * If both are Valid, returns Valid containing a tuple of both values.
66
+ * If either is Invalid, accumulates all errors.
67
+ *
68
+ * @param valA - The Validation to combine with this one
69
+ * @returns Validation containing a tuple of both values, or accumulated errors
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * valid("Alice").zip(valid(30)) // Valid(["Alice", 30])
74
+ * valid("Alice").zip(invalid("No age")) // Invalid(["No age"])
75
+ * invalid("e1").zip(invalid("e2")) // Invalid(["e1", "e2"])
76
+ * ```
77
+ */
78
+ zip: <EE, A>(valA: Validation<EE, A>) => Validation<E | EE, readonly [T, A]>;
79
+ /**
80
+ * Pattern matches on the Validation, executing different functions based on its state.
81
+ *
82
+ * @param onInvalid - Function to execute if Validation is Invalid, receives the array of errors
83
+ * @param onValid - Function to execute if Validation is Valid, receives the value
84
+ * @returns The result of the executed function
85
+ */
86
+ match: <U>(onInvalid: (errors: readonly E[]) => U, onValid: (value: T) => U) => U;
87
+ /**
88
+ * Extracts the valid value, or returns a fallback value if Invalid.
89
+ *
90
+ * @param fallback - Function that receives the errors and returns a default value
91
+ * @returns The valid value if present, otherwise the result of the fallback function
92
+ */
93
+ getOrElse: (fallback: (errors: readonly E[]) => T) => T;
94
+ /**
95
+ * Performs a side effect if this Validation is Valid, returning the original Validation unchanged.
96
+ * If this Validation is Invalid, the side effect is not executed.
97
+ *
98
+ * @param sideEffect - Function to execute with the valid value (return value is ignored)
99
+ * @returns The same Validation instance unchanged
100
+ */
101
+ tap: (sideEffect: (value: T) => void) => Validation<E, T>;
102
+ /**
103
+ * Performs a side effect if this Validation is Invalid, returning the original Validation unchanged.
104
+ * If this Validation is Valid, the side effect is not executed.
105
+ *
106
+ * @param sideEffect - Function to execute with the errors array (return value is ignored)
107
+ * @returns The same Validation instance unchanged
108
+ */
109
+ tapInvalid: (sideEffect: (errors: readonly E[]) => void) => Validation<E, T>;
110
+ /**
111
+ * Converts the Validation to a ValidationResult type.
112
+ *
113
+ * @returns A ValidationResult object representing the Validation's state
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * valid(42).toResult() // { ok: true, value: 42 }
118
+ * invalid("error").toResult() // { ok: false, errors: ["error"] }
119
+ * ```
120
+ */
121
+ toResult: () => ValidationResult<E, T>;
122
+ };
123
+ //#endregion
124
+ //#region src/validation/constructors.d.ts
125
+ /**
126
+ * Creates a Validation containing a valid value.
127
+ *
128
+ * @param value - The valid value to wrap
129
+ * @returns Validation containing the valid value
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * const v = valid(42); // Validation<never, number>
134
+ * ```
135
+ */
136
+ declare function valid<T, E = never>(value: T): Validation<E, T>;
137
+ /**
138
+ * Creates a Validation containing a single error.
139
+ *
140
+ * @param error - The error to wrap
141
+ * @returns Validation containing the error
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * const v = invalid("Something went wrong"); // Validation<string, never>
146
+ * ```
147
+ */
148
+ declare function invalid<E, T = never>(error: E): Validation<E, T>;
149
+ /**
150
+ * Creates a Validation from an Either.
151
+ * Right values become Valid, Left values become Invalid (with a single error).
152
+ *
153
+ * @param either - The Either to convert
154
+ * @returns Validation equivalent of the Either
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * fromEither(right(42)) // Valid(42)
159
+ * fromEither(left("error")) // Invalid(["error"])
160
+ * ```
161
+ */
162
+ declare function fromEither<E, T>(either: Either<E, T>): Validation<E, T>;
163
+ /**
164
+ * Creates a Validation from an Option.
165
+ * Some values become Valid, None becomes Invalid with the provided error.
166
+ *
167
+ * @param opt - The Option to convert
168
+ * @param onNone - Function that provides the error when Option is None
169
+ * @returns Validation equivalent of the Option
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * fromOption(some(42), () => "missing") // Valid(42)
174
+ * fromOption(none(), () => "missing") // Invalid(["missing"])
175
+ * ```
176
+ */
177
+ declare function fromOption<E, T>(opt: Option<T>, onNone: () => E): Validation<E, T>;
178
+ //#endregion
179
+ //#region src/validation/helpers.d.ts
180
+ /**
181
+ * Combines two Validations using a mapping function.
182
+ * If both are Valid, applies the mapper. If any are Invalid, accumulates all errors.
183
+ *
184
+ * @param valA - First Validation to combine
185
+ * @param valB - Second Validation to combine
186
+ * @param mapper - Function to combine both valid values
187
+ * @returns Validation containing the mapped result, or all accumulated errors
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * map2(valid("John"), valid("Doe"), (first, last) => `${first} ${last}`)
192
+ * // Valid("John Doe")
193
+ * map2(invalid("e1"), invalid("e2"), mapper)
194
+ * // Invalid(["e1", "e2"])
195
+ * ```
196
+ */
197
+ declare function map2<EA, A, EB, B, C>(valA: Validation<EA, A>, valB: Validation<EB, B>, mapper: (a: A, b: B) => C): Validation<EA | EB, C>;
198
+ /**
199
+ * Combines three Validations using a mapping function.
200
+ * If all are Valid, applies the mapper. If any are Invalid, accumulates all errors.
201
+ *
202
+ * @param valA - First Validation to combine
203
+ * @param valB - Second Validation to combine
204
+ * @param valC - Third Validation to combine
205
+ * @param mapper - Function to combine all three valid values
206
+ * @returns Validation containing the mapped result, or all accumulated errors
207
+ *
208
+ * @example
209
+ * ```typescript
210
+ * map3(valid(1), valid(2), valid(3), (a, b, c) => a + b + c)
211
+ * // Valid(6)
212
+ * map3(invalid("e1"), valid(2), invalid("e3"), mapper)
213
+ * // Invalid(["e1", "e3"])
214
+ * ```
215
+ */
216
+ declare function map3<EA, A, EB, B, EC, C, D>(valA: Validation<EA, A>, valB: Validation<EB, B>, valC: Validation<EC, C>, mapper: (a: A, b: B, c: C) => D): Validation<EA | EB | EC, D>;
217
+ /**
218
+ * Converts an array of Validations into a Validation of array.
219
+ * Returns Valid with all values if all Validations are Valid, otherwise accumulates all errors.
220
+ *
221
+ * @param validations - Array of Validations to sequence
222
+ * @returns Validation containing array of all values, or all accumulated errors
223
+ *
224
+ * @example
225
+ * ```typescript
226
+ * sequence([valid(1), valid(2), valid(3)]) // Valid([1, 2, 3])
227
+ * sequence([valid(1), invalid("e1"), invalid("e2")]) // Invalid(["e1", "e2"])
228
+ * ```
229
+ */
230
+ declare function sequence<E, T>(validations: readonly Validation<E, T>[]): Validation<E, T[]>;
15
231
  //#endregion
16
- export { Validation, ValidationV, fromEither, invalid, sequence, traverse, valid };
232
+ export { Invalid, Valid, type Validation, ValidationResult, ValidationValue, fromEither, fromOption, invalid, map2, map3, sequence, valid };
@@ -1,19 +1,165 @@
1
- //#region src/validation.ts
2
- function valid() {
3
- throw new Error("Not implemented");
1
+ //#region src/validation/validation.ts
2
+ function createValidation(value) {
3
+ const validation = {
4
+ filterOrElse: (predicate, onInvalid) => validation.match(() => validation, (v) => predicate(v) ? validation : createValidation({ invalid: [onInvalid()] })),
5
+ map: (mapper) => validation.match(() => forceCast(validation), (v) => createValidation({ valid: mapper(v) })),
6
+ ap: function(arg) {
7
+ return this.match((errors1) => arg.match((errors2) => createValidation({ invalid: [...errors1, ...errors2] }), () => createValidation({ invalid: errors1 })), (fn) => arg.match((errors2) => createValidation({ invalid: errors2 }), (v) => createValidation({ valid: fn(v) })));
8
+ },
9
+ zip: (valA) => validation.map((value) => (a) => [value, a]).ap(valA),
10
+ match: (onInvalid, onValid) => isValid(value) ? onValid(value.valid) : onInvalid(value.invalid),
11
+ getOrElse: (fallback) => validation.match((errors) => fallback(errors), (v) => v),
12
+ tap: (sideEffect) => {
13
+ validation.match(() => {}, sideEffect);
14
+ return validation;
15
+ },
16
+ tapInvalid: (sideEffect) => {
17
+ validation.match(sideEffect, () => {});
18
+ return validation;
19
+ },
20
+ toResult: () => validation.match((errors) => ({
21
+ ok: false,
22
+ errors
23
+ }), (value) => ({
24
+ ok: true,
25
+ value
26
+ }))
27
+ };
28
+ return validation;
4
29
  }
5
- function invalid() {
6
- throw new Error("Not implemented");
30
+ function isValid(value) {
31
+ return typeof value === "object" && "valid" in value;
7
32
  }
8
- function fromEither(_either) {
9
- throw new Error("Not implemented");
33
+ function forceCast(v) {
34
+ return v;
10
35
  }
11
- function traverse() {
12
- throw new Error("Not implemented");
36
+
37
+ //#endregion
38
+ //#region src/validation/constructors.ts
39
+ /**
40
+ * Creates a Validation containing a valid value.
41
+ *
42
+ * @param value - The valid value to wrap
43
+ * @returns Validation containing the valid value
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const v = valid(42); // Validation<never, number>
48
+ * ```
49
+ */
50
+ function valid(value) {
51
+ return createValidation({ valid: value });
52
+ }
53
+ /**
54
+ * Creates a Validation containing a single error.
55
+ *
56
+ * @param error - The error to wrap
57
+ * @returns Validation containing the error
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * const v = invalid("Something went wrong"); // Validation<string, never>
62
+ * ```
63
+ */
64
+ function invalid(error) {
65
+ return createValidation({ invalid: [error] });
66
+ }
67
+ /**
68
+ * Creates a Validation from an Either.
69
+ * Right values become Valid, Left values become Invalid (with a single error).
70
+ *
71
+ * @param either - The Either to convert
72
+ * @returns Validation equivalent of the Either
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * fromEither(right(42)) // Valid(42)
77
+ * fromEither(left("error")) // Invalid(["error"])
78
+ * ```
79
+ */
80
+ function fromEither(either) {
81
+ return either.match((error) => invalid(error), (value) => valid(value));
82
+ }
83
+ /**
84
+ * Creates a Validation from an Option.
85
+ * Some values become Valid, None becomes Invalid with the provided error.
86
+ *
87
+ * @param opt - The Option to convert
88
+ * @param onNone - Function that provides the error when Option is None
89
+ * @returns Validation equivalent of the Option
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * fromOption(some(42), () => "missing") // Valid(42)
94
+ * fromOption(none(), () => "missing") // Invalid(["missing"])
95
+ * ```
96
+ */
97
+ function fromOption(opt, onNone) {
98
+ return opt.match(() => invalid(onNone()), (value) => valid(value));
99
+ }
100
+
101
+ //#endregion
102
+ //#region src/validation/helpers.ts
103
+ /**
104
+ * Combines two Validations using a mapping function.
105
+ * If both are Valid, applies the mapper. If any are Invalid, accumulates all errors.
106
+ *
107
+ * @param valA - First Validation to combine
108
+ * @param valB - Second Validation to combine
109
+ * @param mapper - Function to combine both valid values
110
+ * @returns Validation containing the mapped result, or all accumulated errors
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * map2(valid("John"), valid("Doe"), (first, last) => `${first} ${last}`)
115
+ * // Valid("John Doe")
116
+ * map2(invalid("e1"), invalid("e2"), mapper)
117
+ * // Invalid(["e1", "e2"])
118
+ * ```
119
+ */
120
+ function map2(valA, valB, mapper) {
121
+ return valA.map((a) => (b) => mapper(a, b)).ap(valB);
122
+ }
123
+ /**
124
+ * Combines three Validations using a mapping function.
125
+ * If all are Valid, applies the mapper. If any are Invalid, accumulates all errors.
126
+ *
127
+ * @param valA - First Validation to combine
128
+ * @param valB - Second Validation to combine
129
+ * @param valC - Third Validation to combine
130
+ * @param mapper - Function to combine all three valid values
131
+ * @returns Validation containing the mapped result, or all accumulated errors
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * map3(valid(1), valid(2), valid(3), (a, b, c) => a + b + c)
136
+ * // Valid(6)
137
+ * map3(invalid("e1"), valid(2), invalid("e3"), mapper)
138
+ * // Invalid(["e1", "e3"])
139
+ * ```
140
+ */
141
+ function map3(valA, valB, valC, mapper) {
142
+ return valA.map((a) => (b) => (c) => mapper(a, b, c)).ap(valB).ap(valC);
13
143
  }
14
- function sequence() {
15
- throw new Error("Not implemented");
144
+ /**
145
+ * Converts an array of Validations into a Validation of array.
146
+ * Returns Valid with all values if all Validations are Valid, otherwise accumulates all errors.
147
+ *
148
+ * @param validations - Array of Validations to sequence
149
+ * @returns Validation containing array of all values, or all accumulated errors
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * sequence([valid(1), valid(2), valid(3)]) // Valid([1, 2, 3])
154
+ * sequence([valid(1), invalid("e1"), invalid("e2")]) // Invalid(["e1", "e2"])
155
+ * ```
156
+ */
157
+ function sequence(validations) {
158
+ const errors = [];
159
+ const values = [];
160
+ for (const v of validations) v.match((errs) => errors.push(...errs), (value) => values.push(value));
161
+ return errors.length > 0 ? createValidation({ invalid: errors }) : createValidation({ valid: values });
16
162
  }
17
163
 
18
164
  //#endregion
19
- export { fromEither, invalid, sequence, traverse, valid };
165
+ export { fromEither, fromOption, invalid, map2, map3, sequence, valid };
package/package.json CHANGED
@@ -1,61 +1,69 @@
1
1
  {
2
- "name": "ok-fp",
3
- "version": "0.0.1",
4
- "description": "Essential typed effects for TypeScript.",
5
- "keywords": [
6
- "typescript",
7
- "fp",
8
- "functional-programming",
9
- "effects",
10
- "algebraic-data-types",
11
- "monads",
12
- "option",
13
- "either",
14
- "validation",
15
- "task",
16
- "taskEither"
17
- ],
18
- "homepage": "https://github.com/pwlmc/okfp#readme",
19
- "bugs": {
20
- "url": "https://github.com/pwlmc/okfp/issues"
21
- },
22
- "repository": {
23
- "type": "git",
24
- "url": "git+https://github.com/pwlmc/okfp.git"
25
- },
26
- "license": "MIT",
27
- "author": "pwlmc",
28
- "type": "module",
29
- "main": "dist/",
30
- "exports": {
31
- "./either": {
32
- "types": "./dist/either.d.mts",
33
- "default": "./dist/either.mjs"
34
- },
35
- "./option": {
36
- "types": "./dist/option.mts",
37
- "default": "./dist/option.mjs"
38
- }
39
- },
40
- "files": [
41
- "dist"
42
- ],
43
- "scripts": {
44
- "lint": "biome check src/",
45
- "test": "vitest",
46
- "typecheck": "tsc --noEmit",
47
- "build": "tsdown --format esm --dts",
48
- "dev": "tsdown --format esm --dts --watch",
49
- "docs:dev": "vitepress dev docs",
50
- "docs:build": "vitepress build docs",
51
- "docs:preview": "vitepress preview docs"
52
- },
53
- "devDependencies": {
54
- "@biomejs/biome": "^2.4.4",
55
- "@vitest/coverage-v8": "^4.0.18",
56
- "tsdown": "^0.20.3",
57
- "typescript": "^5.9.3",
58
- "vitepress": "^1.6.4",
59
- "vitest": "^4.0.18"
60
- }
2
+ "name": "ok-fp",
3
+ "version": "0.2.1",
4
+ "description": "Essential Effect Data Types for TypeScript",
5
+ "keywords": [
6
+ "typescript",
7
+ "fp",
8
+ "functional-programming",
9
+ "effects",
10
+ "algebraic-data-types",
11
+ "monads",
12
+ "option",
13
+ "either",
14
+ "validation",
15
+ "task",
16
+ "taskEither"
17
+ ],
18
+ "homepage": "https://github.com/pwlmc/ok-fp#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/pwlmc/ok-fp/issues"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/pwlmc/ok-fp.git"
25
+ },
26
+ "license": "MIT",
27
+ "author": "pwlmc",
28
+ "type": "module",
29
+ "main": "dist/",
30
+ "exports": {
31
+ "./either": {
32
+ "types": "./dist/either.d.mts",
33
+ "default": "./dist/either.mjs"
34
+ },
35
+ "./option": {
36
+ "types": "./dist/option.d.mts",
37
+ "default": "./dist/option.mjs"
38
+ },
39
+ "./validation": {
40
+ "types": "./dist/validation.d.mts",
41
+ "default": "./dist/validation.mjs"
42
+ },
43
+ "./task": {
44
+ "types": "./dist/task.d.mts",
45
+ "default": "./dist/task.mjs"
46
+ }
47
+ },
48
+ "files": [
49
+ "dist"
50
+ ],
51
+ "scripts": {
52
+ "lint": "biome check src/",
53
+ "test": "vitest",
54
+ "typecheck": "tsc --noEmit",
55
+ "build": "tsdown --format esm --dts",
56
+ "dev": "tsdown --format esm --dts --watch",
57
+ "docs:dev": "vitepress dev docs",
58
+ "docs:build": "vitepress build docs",
59
+ "docs:preview": "vitepress preview docs"
60
+ },
61
+ "devDependencies": {
62
+ "@biomejs/biome": "^2.4.4",
63
+ "@vitest/coverage-v8": "^4.0.18",
64
+ "tsdown": "^0.20.3",
65
+ "typescript": "^5.9.3",
66
+ "vitepress": "^1.6.4",
67
+ "vitest": "^4.0.18"
68
+ }
61
69
  }