nalloc 0.0.3 → 0.2.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 +56 -8
- package/build/iter.cjs +6 -8
- package/build/iter.cjs.map +1 -1
- package/build/iter.js +6 -8
- package/build/iter.js.map +1 -1
- package/build/option.cjs +16 -8
- package/build/option.cjs.map +1 -1
- package/build/option.d.ts +12 -2
- package/build/option.js +13 -8
- package/build/option.js.map +1 -1
- package/build/result.cjs +102 -24
- package/build/result.cjs.map +1 -1
- package/build/result.d.ts +96 -14
- package/build/result.js +87 -21
- package/build/result.js.map +1 -1
- package/build/safe.cjs +16 -0
- package/build/safe.cjs.map +1 -1
- package/build/safe.d.ts +22 -1
- package/build/safe.js +8 -1
- package/build/safe.js.map +1 -1
- package/build/types.cjs +2 -2
- package/build/types.cjs.map +1 -1
- package/build/types.d.ts +1 -0
- package/build/types.js +2 -2
- package/build/types.js.map +1 -1
- package/package.json +29 -10
- package/src/__tests__/index.ts +34 -0
- package/src/__tests__/option.ts +23 -1
- package/src/__tests__/option.types.ts +2 -1
- package/src/__tests__/result.ts +194 -1
- package/src/__tests__/result.types.ts +18 -5
- package/src/iter.ts +4 -2
- package/src/option.ts +23 -7
- package/src/result.ts +188 -37
- package/src/safe.ts +49 -1
- package/src/types.ts +4 -2
package/README.md
CHANGED
|
@@ -107,6 +107,40 @@ import { Option } from 'nalloc';
|
|
|
107
107
|
Option.map(42, x => x * 2); // value IS the Option
|
|
108
108
|
```
|
|
109
109
|
|
|
110
|
+
### From oxide.ts
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
// oxide.ts
|
|
114
|
+
import { Some, None, Ok, Err } from 'oxide.ts';
|
|
115
|
+
const opt = Some(42);
|
|
116
|
+
opt.map(x => x * 2);
|
|
117
|
+
const result = Ok(42);
|
|
118
|
+
result.mapErr(e => new Error(e));
|
|
119
|
+
|
|
120
|
+
// nalloc - no wrapper objects on the happy path
|
|
121
|
+
import { Option, Result, ok } from 'nalloc';
|
|
122
|
+
Option.map(42, x => x * 2); // 42 is the Option itself
|
|
123
|
+
const result = ok(42); // zero allocation
|
|
124
|
+
Result.mapErr(result, e => new Error(e));
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### From ts-results
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
// ts-results
|
|
131
|
+
import { Ok, Err, Some, None } from 'ts-results';
|
|
132
|
+
const result = new Ok(42);
|
|
133
|
+
result.map(x => x * 2);
|
|
134
|
+
const opt = Some(42);
|
|
135
|
+
opt.unwrapOr(0);
|
|
136
|
+
|
|
137
|
+
// nalloc - same safety, zero allocations
|
|
138
|
+
import { Option, Result, ok } from 'nalloc';
|
|
139
|
+
const result = ok(42); // no wrapper
|
|
140
|
+
Result.map(result, x => x * 2);
|
|
141
|
+
Option.unwrapOr(42, 0); // value IS the Option
|
|
142
|
+
```
|
|
143
|
+
|
|
110
144
|
### From Rust
|
|
111
145
|
|
|
112
146
|
The API mirrors Rust's `Option` and `Result`:
|
|
@@ -350,14 +384,28 @@ Iter.tryForEach(items, item => processItem(item));
|
|
|
350
384
|
|
|
351
385
|
## Comparison
|
|
352
386
|
|
|
353
|
-
| Feature | nalloc | neverthrow | fp-ts | oxide.ts |
|
|
354
|
-
|
|
355
|
-
| Zero-alloc Option | Yes | No | No | No |
|
|
356
|
-
| Zero-alloc Ok | Yes | No | No | No |
|
|
357
|
-
| Bundle size | Tiny | Small | Large | Small |
|
|
358
|
-
| Learning curve | Low | Low | High | Low |
|
|
359
|
-
| Async support | Yes | Yes | Yes | Limited |
|
|
360
|
-
| Tree-shakeable | Yes | Yes | Yes | Yes |
|
|
387
|
+
| Feature | nalloc | neverthrow | fp-ts | oxide.ts | ts-results |
|
|
388
|
+
|---------|---------|------------|-------|----------|------------|
|
|
389
|
+
| Zero-alloc Option | Yes | No | No | No | No |
|
|
390
|
+
| Zero-alloc Ok | Yes | No | No | No | No |
|
|
391
|
+
| Bundle size | Tiny | Small | Large | Small | Small |
|
|
392
|
+
| Learning curve | Low | Low | High | Low | Low |
|
|
393
|
+
| Async support | Yes | Yes | Yes | Limited | No |
|
|
394
|
+
| Tree-shakeable | Yes | Yes | Yes | Yes | Yes |
|
|
395
|
+
| Iterator utilities | Yes | No | Yes | No | No |
|
|
396
|
+
| safeTry (? operator) | Yes | Yes | No | No | No |
|
|
397
|
+
|
|
398
|
+
## Alternatives
|
|
399
|
+
|
|
400
|
+
Looking for a TypeScript Result/Option library? Here's how nalloc compares:
|
|
401
|
+
|
|
402
|
+
- **neverthrow** - Popular, method-chaining API. Allocates a wrapper for every Ok and Err. nalloc avoids allocation on the happy path entirely.
|
|
403
|
+
- **fp-ts / effect** - Full functional programming ecosystem with Either and Option. Powerful but heavy and steep learning curve. nalloc focuses on Result/Option with a simpler API.
|
|
404
|
+
- **oxide.ts** - Rust-inspired with class-based wrappers. Every Some/Ok allocates an object. nalloc represents Some/Ok as the raw value.
|
|
405
|
+
- **ts-results / ts-results-es** - Direct Rust port with class instances. Similar API surface to nalloc, but allocates on every construction.
|
|
406
|
+
- **true-myth** - Result and Maybe with a functional API. Wraps all values. nalloc is a similar philosophy with zero-allocation design.
|
|
407
|
+
|
|
408
|
+
nalloc is designed for codebases where allocation pressure matters - high-throughput servers, hot loops, and performance-sensitive paths - while keeping the same safety guarantees.
|
|
361
409
|
|
|
362
410
|
## License
|
|
363
411
|
|
package/build/iter.cjs
CHANGED
|
@@ -26,6 +26,10 @@ _export(exports, {
|
|
|
26
26
|
}
|
|
27
27
|
});
|
|
28
28
|
const _typescjs = require("./types.cjs");
|
|
29
|
+
const ITER_DONE = Object.freeze({
|
|
30
|
+
value: undefined,
|
|
31
|
+
done: true
|
|
32
|
+
});
|
|
29
33
|
function* mapWhile(source, fn) {
|
|
30
34
|
for (const item of source){
|
|
31
35
|
const mapped = fn(item);
|
|
@@ -41,10 +45,7 @@ function safeIter(source) {
|
|
|
41
45
|
return this;
|
|
42
46
|
},
|
|
43
47
|
next () {
|
|
44
|
-
if (done) return
|
|
45
|
-
value: undefined,
|
|
46
|
-
done: true
|
|
47
|
-
};
|
|
48
|
+
if (done) return ITER_DONE;
|
|
48
49
|
try {
|
|
49
50
|
const next = iter.next();
|
|
50
51
|
if (next.done) {
|
|
@@ -70,10 +71,7 @@ function safeIter(source) {
|
|
|
70
71
|
iter.return?.();
|
|
71
72
|
} catch {}
|
|
72
73
|
}
|
|
73
|
-
return
|
|
74
|
-
value: undefined,
|
|
75
|
-
done: true
|
|
76
|
-
};
|
|
74
|
+
return ITER_DONE;
|
|
77
75
|
}
|
|
78
76
|
};
|
|
79
77
|
}
|
package/build/iter.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/iter.ts"],"sourcesContent":["import { isSome, isErr, err as ERR } from './types.js';\nimport type { Option, Result, Ok } from './types.js';\n\n/**\n * Yields mapped values while the mapping function returns Some, stops at the first None.\n * @param source - The iterable to map over\n * @param fn - Mapping function returning Some(value) to continue or None to stop\n * @returns Generator of mapped values\n * @example\n * [...mapWhile([1, 2, 3, 4], n => n < 3 ? some(n * 10) : none)] // [10, 20]\n */\nexport function* mapWhile<T, U>(source: Iterable<T>, fn: (value: T) => Option<U>): Generator<U> {\n for (const item of source) {\n const mapped = fn(item);\n if (!isSome(mapped)) return;\n yield mapped as U;\n }\n}\n\n/**\n * Wraps an iterable so that each yielded value becomes Ok and any throw becomes a single Err.\n * Stops after the first error - the source's internal state is unknown after an exception.\n *\n * Uses a manual iterator instead of a generator to avoid coroutine suspend/resume overhead.\n *\n * Follows the for-of IteratorClose spec:\n * - iter.return() is never called on natural exhaustion or after a caught error\n * - iter.return() is only called on early consumer exit (break/return)\n * - Cleanup errors from iter.return() are suppressed\n *\n * @param source - The iterable to wrap\n * @returns Iterable iterator of Result values\n * @example\n * [...safeIter([1, 2, 3])] // [Ok(1), Ok(2), Ok(3)]\n * [...safeIter(throwingIter())] // [Ok(1), Err(error)]\n */\nexport function safeIter<T>(source: Iterable<T>): IterableIterator<Result<T, unknown>> {\n const iter = source[Symbol.iterator]();\n let done = false;\n return {\n [Symbol.iterator]() {\n return this;\n },\n next(): IteratorResult<Result<T, unknown>> {\n if (done) return
|
|
1
|
+
{"version":3,"sources":["../src/iter.ts"],"sourcesContent":["import { isSome, isErr, err as ERR } from './types.js';\nimport type { Option, Result, Ok } from './types.js';\n\nconst ITER_DONE: IteratorResult<never> = Object.freeze({ value: undefined as never, done: true as const });\n\n/**\n * Yields mapped values while the mapping function returns Some, stops at the first None.\n * @param source - The iterable to map over\n * @param fn - Mapping function returning Some(value) to continue or None to stop\n * @returns Generator of mapped values\n * @example\n * [...mapWhile([1, 2, 3, 4], n => n < 3 ? some(n * 10) : none)] // [10, 20]\n */\nexport function* mapWhile<T, U>(source: Iterable<T>, fn: (value: T) => Option<U>): Generator<U> {\n for (const item of source) {\n const mapped = fn(item);\n if (!isSome(mapped)) return;\n yield mapped as U;\n }\n}\n\n/**\n * Wraps an iterable so that each yielded value becomes Ok and any throw becomes a single Err.\n * Stops after the first error - the source's internal state is unknown after an exception.\n *\n * Uses a manual iterator instead of a generator to avoid coroutine suspend/resume overhead.\n *\n * Follows the for-of IteratorClose spec:\n * - iter.return() is never called on natural exhaustion or after a caught error\n * - iter.return() is only called on early consumer exit (break/return)\n * - Cleanup errors from iter.return() are suppressed\n *\n * @param source - The iterable to wrap\n * @returns Iterable iterator of Result values\n * @example\n * [...safeIter([1, 2, 3])] // [Ok(1), Ok(2), Ok(3)]\n * [...safeIter(throwingIter())] // [Ok(1), Err(error)]\n */\nexport function safeIter<T>(source: Iterable<T>): IterableIterator<Result<T, unknown>> {\n const iter = source[Symbol.iterator]();\n let done = false;\n return {\n [Symbol.iterator]() {\n return this;\n },\n next(): IteratorResult<Result<T, unknown>> {\n if (done) return ITER_DONE;\n try {\n const next = iter.next();\n if (next.done) {\n done = true;\n return next;\n }\n return { value: next.value as Ok<T>, done: false };\n } catch (e) {\n done = true;\n return { value: ERR(e), done: false };\n }\n },\n return(): IteratorResult<Result<T, unknown>> {\n if (!done) {\n done = true;\n try {\n iter.return?.();\n } catch {\n // suppressed\n }\n }\n return ITER_DONE;\n },\n };\n}\n\n// -- Result-oriented terminal operations --\n\n/**\n * Collects an iterable of Results into a single Result containing an array.\n * Short-circuits on the first Err.\n * @param source - Iterable of Result values\n * @returns Ok(values[]) if all Ok, or the first Err encountered\n * @example\n * tryCollect([ok(1), ok(2), ok(3)]) // Ok([1, 2, 3])\n * tryCollect([ok(1), err('x')]) // Err('x')\n */\nexport function tryCollect<T, E>(source: Iterable<Result<T, E>>): Result<T[], E> {\n const collected: T[] = [];\n for (const result of source) {\n if (isErr(result)) return result;\n collected.push(result as T);\n }\n return collected as Ok<T[]>;\n}\n\n/**\n * Folds an iterable with a fallible accumulator function.\n * Short-circuits on the first Err returned by fn.\n * @param source - The iterable to fold over\n * @param init - Initial accumulator value\n * @param fn - Folding function returning Ok(newAcc) or Err\n * @returns Ok(finalAcc) if all steps succeed, or the first Err\n * @example\n * tryFold([1, 2, 3], 0, (acc, n) => ok(acc + n)) // Ok(6)\n * tryFold([1, 2, 3], 0, (acc, n) => n === 2 ? err('stop') : ok(acc + n)) // Err('stop')\n */\nexport function tryFold<T, Acc, E>(source: Iterable<T>, init: Acc, fn: (acc: Acc, item: T) => Result<Acc, E>): Result<Acc, E> {\n let acc = init;\n for (const item of source) {\n const result = fn(acc, item);\n if (isErr(result)) return result;\n acc = result as Acc;\n }\n return acc as Ok<Acc>;\n}\n\n/**\n * Iterates over a source, calling a fallible function for each item.\n * Short-circuits on the first Err returned by fn.\n * @param source - The iterable to iterate over\n * @param fn - Function to call for each item, returning Ok(void) or Err\n * @returns Ok(void) if all calls succeed, or the first Err\n * @example\n * tryForEach([1, 2, 3], n => ok(console.log(n))) // Ok(void), logs 1, 2, 3\n * tryForEach([1, 2, 3], n => n === 2 ? err('stop') : ok(undefined)) // Err('stop')\n */\nexport function tryForEach<T, E>(source: Iterable<T>, fn: (item: T) => Result<void, E>): Result<void, E> {\n for (const item of source) {\n const result = fn(item);\n if (isErr(result)) return result;\n }\n return undefined as Ok<void>;\n}\n"],"names":["mapWhile","safeIter","tryCollect","tryFold","tryForEach","ITER_DONE","Object","freeze","value","undefined","done","source","fn","item","mapped","isSome","iter","Symbol","iterator","next","e","ERR","return","collected","result","isErr","push","init","acc"],"mappings":";;;;;;;;;;;QAaiBA;eAAAA;;QAyBDC;eAAAA;;QA8CAC;eAAAA;;QAoBAC;eAAAA;;QAoBAC;eAAAA;;;0BA5H0B;AAG1C,MAAMC,YAAmCC,OAAOC,MAAM,CAAC;IAAEC,OAAOC;IAAoBC,MAAM;AAAc;AAUjG,UAAUV,SAAeW,MAAmB,EAAEC,EAA2B;IAC9E,KAAK,MAAMC,QAAQF,OAAQ;QACzB,MAAMG,SAASF,GAAGC;QAClB,IAAI,CAACE,IAAAA,gBAAM,EAACD,SAAS;QACrB,MAAMA;IACR;AACF;AAmBO,SAASb,SAAYU,MAAmB;IAC7C,MAAMK,OAAOL,MAAM,CAACM,OAAOC,QAAQ,CAAC;IACpC,IAAIR,OAAO;IACX,OAAO;QACL,CAACO,OAAOC,QAAQ,CAAC;YACf,OAAO,IAAI;QACb;QACAC;YACE,IAAIT,MAAM,OAAOL;YACjB,IAAI;gBACF,MAAMc,OAAOH,KAAKG,IAAI;gBACtB,IAAIA,KAAKT,IAAI,EAAE;oBACbA,OAAO;oBACP,OAAOS;gBACT;gBACA,OAAO;oBAAEX,OAAOW,KAAKX,KAAK;oBAAWE,MAAM;gBAAM;YACnD,EAAE,OAAOU,GAAG;gBACVV,OAAO;gBACP,OAAO;oBAAEF,OAAOa,IAAAA,aAAG,EAACD;oBAAIV,MAAM;gBAAM;YACtC;QACF;QACAY;YACE,IAAI,CAACZ,MAAM;gBACTA,OAAO;gBACP,IAAI;oBACFM,KAAKM,MAAM;gBACb,EAAE,OAAM,CAER;YACF;YACA,OAAOjB;QACT;IACF;AACF;AAaO,SAASH,WAAiBS,MAA8B;IAC7D,MAAMY,YAAiB,EAAE;IACzB,KAAK,MAAMC,UAAUb,OAAQ;QAC3B,IAAIc,IAAAA,eAAK,EAACD,SAAS,OAAOA;QAC1BD,UAAUG,IAAI,CAACF;IACjB;IACA,OAAOD;AACT;AAaO,SAASpB,QAAmBQ,MAAmB,EAAEgB,IAAS,EAAEf,EAAyC;IAC1G,IAAIgB,MAAMD;IACV,KAAK,MAAMd,QAAQF,OAAQ;QACzB,MAAMa,SAASZ,GAAGgB,KAAKf;QACvB,IAAIY,IAAAA,eAAK,EAACD,SAAS,OAAOA;QAC1BI,MAAMJ;IACR;IACA,OAAOI;AACT;AAYO,SAASxB,WAAiBO,MAAmB,EAAEC,EAAgC;IACpF,KAAK,MAAMC,QAAQF,OAAQ;QACzB,MAAMa,SAASZ,GAAGC;QAClB,IAAIY,IAAAA,eAAK,EAACD,SAAS,OAAOA;IAC5B;IACA,OAAOf;AACT"}
|
package/build/iter.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { isSome, isErr, err as ERR } from "./types.js";
|
|
2
|
+
const ITER_DONE = Object.freeze({
|
|
3
|
+
value: undefined,
|
|
4
|
+
done: true
|
|
5
|
+
});
|
|
2
6
|
export function* mapWhile(source, fn) {
|
|
3
7
|
for (const item of source){
|
|
4
8
|
const mapped = fn(item);
|
|
@@ -14,10 +18,7 @@ export function safeIter(source) {
|
|
|
14
18
|
return this;
|
|
15
19
|
},
|
|
16
20
|
next () {
|
|
17
|
-
if (done) return
|
|
18
|
-
value: undefined,
|
|
19
|
-
done: true
|
|
20
|
-
};
|
|
21
|
+
if (done) return ITER_DONE;
|
|
21
22
|
try {
|
|
22
23
|
const next = iter.next();
|
|
23
24
|
if (next.done) {
|
|
@@ -43,10 +44,7 @@ export function safeIter(source) {
|
|
|
43
44
|
iter.return?.();
|
|
44
45
|
} catch {}
|
|
45
46
|
}
|
|
46
|
-
return
|
|
47
|
-
value: undefined,
|
|
48
|
-
done: true
|
|
49
|
-
};
|
|
47
|
+
return ITER_DONE;
|
|
50
48
|
}
|
|
51
49
|
};
|
|
52
50
|
}
|
package/build/iter.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/iter.ts"],"sourcesContent":["import { isSome, isErr, err as ERR } from './types.js';\nimport type { Option, Result, Ok } from './types.js';\n\n/**\n * Yields mapped values while the mapping function returns Some, stops at the first None.\n * @param source - The iterable to map over\n * @param fn - Mapping function returning Some(value) to continue or None to stop\n * @returns Generator of mapped values\n * @example\n * [...mapWhile([1, 2, 3, 4], n => n < 3 ? some(n * 10) : none)] // [10, 20]\n */\nexport function* mapWhile<T, U>(source: Iterable<T>, fn: (value: T) => Option<U>): Generator<U> {\n for (const item of source) {\n const mapped = fn(item);\n if (!isSome(mapped)) return;\n yield mapped as U;\n }\n}\n\n/**\n * Wraps an iterable so that each yielded value becomes Ok and any throw becomes a single Err.\n * Stops after the first error - the source's internal state is unknown after an exception.\n *\n * Uses a manual iterator instead of a generator to avoid coroutine suspend/resume overhead.\n *\n * Follows the for-of IteratorClose spec:\n * - iter.return() is never called on natural exhaustion or after a caught error\n * - iter.return() is only called on early consumer exit (break/return)\n * - Cleanup errors from iter.return() are suppressed\n *\n * @param source - The iterable to wrap\n * @returns Iterable iterator of Result values\n * @example\n * [...safeIter([1, 2, 3])] // [Ok(1), Ok(2), Ok(3)]\n * [...safeIter(throwingIter())] // [Ok(1), Err(error)]\n */\nexport function safeIter<T>(source: Iterable<T>): IterableIterator<Result<T, unknown>> {\n const iter = source[Symbol.iterator]();\n let done = false;\n return {\n [Symbol.iterator]() {\n return this;\n },\n next(): IteratorResult<Result<T, unknown>> {\n if (done) return
|
|
1
|
+
{"version":3,"sources":["../src/iter.ts"],"sourcesContent":["import { isSome, isErr, err as ERR } from './types.js';\nimport type { Option, Result, Ok } from './types.js';\n\nconst ITER_DONE: IteratorResult<never> = Object.freeze({ value: undefined as never, done: true as const });\n\n/**\n * Yields mapped values while the mapping function returns Some, stops at the first None.\n * @param source - The iterable to map over\n * @param fn - Mapping function returning Some(value) to continue or None to stop\n * @returns Generator of mapped values\n * @example\n * [...mapWhile([1, 2, 3, 4], n => n < 3 ? some(n * 10) : none)] // [10, 20]\n */\nexport function* mapWhile<T, U>(source: Iterable<T>, fn: (value: T) => Option<U>): Generator<U> {\n for (const item of source) {\n const mapped = fn(item);\n if (!isSome(mapped)) return;\n yield mapped as U;\n }\n}\n\n/**\n * Wraps an iterable so that each yielded value becomes Ok and any throw becomes a single Err.\n * Stops after the first error - the source's internal state is unknown after an exception.\n *\n * Uses a manual iterator instead of a generator to avoid coroutine suspend/resume overhead.\n *\n * Follows the for-of IteratorClose spec:\n * - iter.return() is never called on natural exhaustion or after a caught error\n * - iter.return() is only called on early consumer exit (break/return)\n * - Cleanup errors from iter.return() are suppressed\n *\n * @param source - The iterable to wrap\n * @returns Iterable iterator of Result values\n * @example\n * [...safeIter([1, 2, 3])] // [Ok(1), Ok(2), Ok(3)]\n * [...safeIter(throwingIter())] // [Ok(1), Err(error)]\n */\nexport function safeIter<T>(source: Iterable<T>): IterableIterator<Result<T, unknown>> {\n const iter = source[Symbol.iterator]();\n let done = false;\n return {\n [Symbol.iterator]() {\n return this;\n },\n next(): IteratorResult<Result<T, unknown>> {\n if (done) return ITER_DONE;\n try {\n const next = iter.next();\n if (next.done) {\n done = true;\n return next;\n }\n return { value: next.value as Ok<T>, done: false };\n } catch (e) {\n done = true;\n return { value: ERR(e), done: false };\n }\n },\n return(): IteratorResult<Result<T, unknown>> {\n if (!done) {\n done = true;\n try {\n iter.return?.();\n } catch {\n // suppressed\n }\n }\n return ITER_DONE;\n },\n };\n}\n\n// -- Result-oriented terminal operations --\n\n/**\n * Collects an iterable of Results into a single Result containing an array.\n * Short-circuits on the first Err.\n * @param source - Iterable of Result values\n * @returns Ok(values[]) if all Ok, or the first Err encountered\n * @example\n * tryCollect([ok(1), ok(2), ok(3)]) // Ok([1, 2, 3])\n * tryCollect([ok(1), err('x')]) // Err('x')\n */\nexport function tryCollect<T, E>(source: Iterable<Result<T, E>>): Result<T[], E> {\n const collected: T[] = [];\n for (const result of source) {\n if (isErr(result)) return result;\n collected.push(result as T);\n }\n return collected as Ok<T[]>;\n}\n\n/**\n * Folds an iterable with a fallible accumulator function.\n * Short-circuits on the first Err returned by fn.\n * @param source - The iterable to fold over\n * @param init - Initial accumulator value\n * @param fn - Folding function returning Ok(newAcc) or Err\n * @returns Ok(finalAcc) if all steps succeed, or the first Err\n * @example\n * tryFold([1, 2, 3], 0, (acc, n) => ok(acc + n)) // Ok(6)\n * tryFold([1, 2, 3], 0, (acc, n) => n === 2 ? err('stop') : ok(acc + n)) // Err('stop')\n */\nexport function tryFold<T, Acc, E>(source: Iterable<T>, init: Acc, fn: (acc: Acc, item: T) => Result<Acc, E>): Result<Acc, E> {\n let acc = init;\n for (const item of source) {\n const result = fn(acc, item);\n if (isErr(result)) return result;\n acc = result as Acc;\n }\n return acc as Ok<Acc>;\n}\n\n/**\n * Iterates over a source, calling a fallible function for each item.\n * Short-circuits on the first Err returned by fn.\n * @param source - The iterable to iterate over\n * @param fn - Function to call for each item, returning Ok(void) or Err\n * @returns Ok(void) if all calls succeed, or the first Err\n * @example\n * tryForEach([1, 2, 3], n => ok(console.log(n))) // Ok(void), logs 1, 2, 3\n * tryForEach([1, 2, 3], n => n === 2 ? err('stop') : ok(undefined)) // Err('stop')\n */\nexport function tryForEach<T, E>(source: Iterable<T>, fn: (item: T) => Result<void, E>): Result<void, E> {\n for (const item of source) {\n const result = fn(item);\n if (isErr(result)) return result;\n }\n return undefined as Ok<void>;\n}\n"],"names":["isSome","isErr","err","ERR","ITER_DONE","Object","freeze","value","undefined","done","mapWhile","source","fn","item","mapped","safeIter","iter","Symbol","iterator","next","e","return","tryCollect","collected","result","push","tryFold","init","acc","tryForEach"],"mappings":"AAAA,SAASA,MAAM,EAAEC,KAAK,EAAEC,OAAOC,GAAG,QAAQ,aAAa;AAGvD,MAAMC,YAAmCC,OAAOC,MAAM,CAAC;IAAEC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OAAO,SAASC,WAAiBlB,MAAmB,EAAEC,EAAgC;IACpF,KAAK,MAAMC,QAAQF,OAAQ;QACzB,MAAMa,SAASZ,GAAGC;QAClB,IAAIZ,MAAMuB,SAAS,OAAOA;IAC5B;IACA,OAAOhB;AACT"}
|
package/build/option.cjs
CHANGED
|
@@ -96,6 +96,9 @@ _export(exports, {
|
|
|
96
96
|
get tap () {
|
|
97
97
|
return tap;
|
|
98
98
|
},
|
|
99
|
+
get tapNone () {
|
|
100
|
+
return tapNone;
|
|
101
|
+
},
|
|
99
102
|
get toArray () {
|
|
100
103
|
return toArray;
|
|
101
104
|
},
|
|
@@ -128,6 +131,10 @@ _export(exports, {
|
|
|
128
131
|
}
|
|
129
132
|
});
|
|
130
133
|
const _typescjs = require("./types.cjs");
|
|
134
|
+
const NONE_PAIR = Object.freeze([
|
|
135
|
+
_typescjs.NONE,
|
|
136
|
+
_typescjs.NONE
|
|
137
|
+
]);
|
|
131
138
|
function fromNullable(value) {
|
|
132
139
|
return (0, _typescjs.optionOf)(value);
|
|
133
140
|
}
|
|
@@ -174,15 +181,19 @@ function map(opt, fn) {
|
|
|
174
181
|
function flatMap(opt, fn) {
|
|
175
182
|
return (0, _typescjs.isNone)(opt) ? _typescjs.NONE : fn(opt);
|
|
176
183
|
}
|
|
177
|
-
|
|
178
|
-
return (0, _typescjs.isNone)(opt) ? _typescjs.NONE : fn(opt);
|
|
179
|
-
}
|
|
184
|
+
const andThen = flatMap;
|
|
180
185
|
function tap(opt, fn) {
|
|
181
186
|
if ((0, _typescjs.isSome)(opt)) {
|
|
182
187
|
fn(opt);
|
|
183
188
|
}
|
|
184
189
|
return opt;
|
|
185
190
|
}
|
|
191
|
+
function tapNone(opt, fn) {
|
|
192
|
+
if ((0, _typescjs.isNone)(opt)) {
|
|
193
|
+
fn();
|
|
194
|
+
}
|
|
195
|
+
return opt;
|
|
196
|
+
}
|
|
186
197
|
function isNoneOr(opt, predicate) {
|
|
187
198
|
return (0, _typescjs.isNone)(opt) || predicate(opt);
|
|
188
199
|
}
|
|
@@ -229,10 +240,7 @@ function zip(opt, other) {
|
|
|
229
240
|
] : _typescjs.NONE;
|
|
230
241
|
}
|
|
231
242
|
function unzip(opt) {
|
|
232
|
-
if ((0, _typescjs.isNone)(opt)) return
|
|
233
|
-
_typescjs.NONE,
|
|
234
|
-
_typescjs.NONE
|
|
235
|
-
];
|
|
243
|
+
if ((0, _typescjs.isNone)(opt)) return NONE_PAIR;
|
|
236
244
|
const [a, b] = opt;
|
|
237
245
|
return [
|
|
238
246
|
(0, _typescjs.optionOf)(a),
|
|
@@ -249,7 +257,7 @@ function flatten(opt) {
|
|
|
249
257
|
return (0, _typescjs.isNone)(opt) ? _typescjs.NONE : opt;
|
|
250
258
|
}
|
|
251
259
|
function contains(opt, value) {
|
|
252
|
-
return (0, _typescjs.isSome)(opt) && opt === value;
|
|
260
|
+
return (0, _typescjs.isSome)(opt) && (opt === value || opt !== opt && value !== value);
|
|
253
261
|
}
|
|
254
262
|
function isSomeAnd(opt, predicate) {
|
|
255
263
|
return (0, _typescjs.isSome)(opt) && predicate(opt);
|
package/build/option.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts"],"sourcesContent":["import { NONE, EMPTY, isSome, isNone, optionOf as of, err, isOk, isErr } from './types.js';\nimport type { Some, None, Option, NoneValueType, ValueType, Result, Ok, Widen } from './types.js';\n\nexport type { Some, None, Option };\nexport { isSome, isNone, of };\n\n/**\n * Creates an Option from a nullable value with widened types.\n * @param value - The value to wrap\n * @returns Some(value) if non-null, None otherwise\n * @example\n * fromNullable(42) // Some(42) with type Option<number>\n * fromNullable(null) // None\n */\nexport function fromNullable(value: null): None;\nexport function fromNullable(value: undefined): None;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>>;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>> {\n return of(value) as Option<Widen<T>>;\n}\n\n/**\n * Creates an Option from a Promise. Resolves to Some if successful, None on rejection.\n * @param promise - The promise to convert\n * @param onRejected - Optional handler for rejected promises\n * @returns Promise resolving to Some(value) or None\n * @example\n * await fromPromise(Promise.resolve(42)) // Some(42)\n * await fromPromise(Promise.reject('error')) // None\n */\nexport async function fromPromise<T>(promise: Promise<T | NoneValueType>, onRejected?: (error: unknown) => T | NoneValueType): Promise<Option<T>> {\n try {\n const value = await promise;\n return of(value as T);\n } catch (error) {\n if (!onRejected) {\n return NONE;\n }\n return of(onRejected(error));\n }\n}\n\n/**\n * Unwraps an Option or returns a computed value if None.\n * @param opt - The Option to unwrap\n * @param onNone - Function called if opt is None\n * @returns The value if Some, or the result of onNone()\n * @example\n * unwrapOrReturn(some(42), () => 0) // 42\n * unwrapOrReturn(none, () => 0) // 0\n */\nexport function unwrapOrReturn<T, R>(opt: Option<T>, onNone: () => R): Widen<T> | R {\n return isSome(opt) ? (opt as Widen<T>) : onNone();\n}\n\n/**\n * Asserts that an Option is Some, throwing if None.\n * @param opt - The Option to assert\n * @param message - Custom error message\n * @throws Error if opt is None\n * @example\n * assertSome(some(42)) // passes\n * assertSome(none) // throws Error\n */\nexport function assertSome<T>(opt: Option<T>, message?: string): asserts opt is Some<ValueType<T>> {\n if (isNone(opt)) {\n throw new Error(message ?? 'Expected Option to contain a value');\n }\n}\n\n/**\n * Compile-time type assertion helper to satisfy Option type constraints.\n *\n * WARNING: This function performs NO runtime validation. It is a no-op at\n * runtime to preserve zero-allocation semantics. Use assertSome() if you\n * need runtime validation that a value is Some.\n *\n * @param _ - The value to assert as Option (not validated at runtime)\n * @example\n * const value: number | null = getValue();\n * satisfiesOption(value); // Compiles, but no runtime check\n * // value is now typed as Option<number>\n */\nexport function satisfiesOption<T>(_: Option<T> | T): asserts _ is Option<T> {\n // Compile-time only - no runtime validation to preserve zero-allocation semantics.\n}\n\n/**\n * Maps and filters an iterable, collecting only Some values.\n * @param values - The iterable to process\n * @param fn - Function that returns Option for each value\n * @returns Array of unwrapped Some values\n * @example\n * filterMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // [4, 6]\n */\nexport function filterMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): U[] {\n const collected: U[] = [];\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) collected.push(mapped);\n }\n return collected;\n}\n\n/**\n * Finds the first element that maps to Some, returning that value.\n * @param values - Iterable to search\n * @param fn - Function that returns Some for matches\n * @returns The first Some value, or None if no match\n * @example\n * findMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // Some(4)\n * findMap([1], n => n > 5 ? some(n) : none) // None\n */\nexport function findMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): Option<U> {\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) return mapped;\n }\n return NONE;\n}\n\n/**\n * Transforms the value inside a Some, or returns None.\n * @param opt - The Option to map\n * @param fn - Transform function\n * @returns Some(fn(value)) if Some, None otherwise\n * @example\n * map(some(2), x => x * 2) // Some(4)\n * map(none, x => x * 2) // None\n */\nexport function map<T, U>(opt: None, fn: (value: T) => U): None;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U>;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U> {\n if (isNone(opt)) return NONE;\n const result = fn(opt);\n return result === null || result === undefined ? NONE : (result as Some<ValueType<U>>);\n}\n\n/**\n * Chains Option-returning functions. Returns None if the input is None.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n * @example\n * flatMap(some(2), x => some(x * 2)) // Some(4)\n * flatMap(some(2), x => none) // None\n * flatMap(none, x => some(x * 2)) // None\n */\nexport function flatMap<T, U>(opt: None, fn: (value: T) => Option<U>): None;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U>;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U> {\n return isNone(opt) ? NONE : fn(opt);\n}\n\n/**\n * Alias for flatMap. Chains Option-returning functions.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n */\nexport function andThen<T, U>(opt: None, fn: (value: T) => Option<U>): None;\nexport function andThen<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U>;\nexport function andThen<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U> {\n return isNone(opt) ? NONE : fn(opt);\n}\n\n/**\n * Executes a side effect if Some, then returns the original Option.\n * @param opt - The Option to tap\n * @param fn - Side effect function\n * @returns The original Option unchanged\n * @example\n * tap(some(42), x => console.log(x)) // logs 42, returns Some(42)\n */\nexport function tap<T>(opt: None, fn: (value: T) => void): None;\nexport function tap<T>(opt: Some<T>, fn: (value: T) => void): Some<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T> {\n if (isSome(opt)) {\n fn(opt);\n }\n return opt;\n}\n\n/**\n * Returns true if None, or if Some and predicate returns true.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if None or predicate(value) is true\n * @example\n * isNoneOr(none, x => x > 2) // true\n * isNoneOr(some(4), x => x > 2) // true\n * isNoneOr(some(1), x => x > 2) // false\n */\nexport function isNoneOr<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isNone(opt) || predicate(opt);\n}\n\n/**\n * Returns Some if the value passes the predicate, None otherwise.\n * @param opt - The Option to filter\n * @param predicate - Test function\n * @returns Some if predicate returns true, None otherwise\n * @example\n * filter(some(4), x => x > 2) // Some(4)\n * filter(some(1), x => x > 2) // None\n */\nexport function filter<T>(opt: None, predicate: (value: T) => boolean): None;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T>;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T> {\n return isSome(opt) && predicate(opt) ? opt : NONE;\n}\n\n/**\n * Extracts the value from Some, throws if None.\n * @param opt - The Option to unwrap\n * @returns The contained value\n * @throws Error if opt is None\n * @example\n * unwrap(some(42)) // 42\n * unwrap(none) // throws Error\n */\nexport function unwrap<T>(opt: Option<T>): T {\n if (isNone(opt)) {\n throw new Error('Called unwrap on None');\n }\n return opt;\n}\n\n/**\n * Extracts the value from Some, or returns a default value.\n * @param opt - The Option to unwrap\n * @param defaultValue - Value to return if None\n * @returns The contained value or defaultValue\n * @example\n * unwrapOr(some(42), 0) // 42\n * unwrapOr(none, 0) // 0\n */\nexport function unwrapOr<T>(opt: Option<T>, defaultValue: T): T {\n return isSome(opt) ? opt : defaultValue;\n}\n\n/**\n * Extracts the value from Some, or computes a default.\n * @param opt - The Option to unwrap\n * @param fn - Function to compute default value\n * @returns The contained value or fn()\n * @example\n * unwrapOrElse(some(42), () => 0) // 42\n * unwrapOrElse(none, () => 0) // 0\n */\nexport function unwrapOrElse<T>(opt: Option<T>, fn: () => T): T {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Extracts the value from Some, throws with custom message if None.\n * @param opt - The Option to unwrap\n * @param message - Error message if None\n * @returns The contained value\n * @throws Error with message if opt is None\n * @example\n * expect(some(42), 'missing value') // 42\n * expect(none, 'missing value') // throws Error('missing value')\n */\nexport function expect<T>(opt: Option<T>, message: string): T {\n if (isNone(opt)) {\n throw new Error(message);\n }\n return opt;\n}\n\n/**\n * Returns the first Some, or the second Option if the first is None.\n * @param opt - First Option\n * @param optb - Fallback Option\n * @returns opt if Some, optb otherwise\n * @example\n * or(some(1), some(2)) // Some(1)\n * or(none, some(2)) // Some(2)\n */\nexport function or<T>(opt: Some<T>, optb: Option<T>): Some<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n return isSome(opt) ? opt : optb;\n}\n\n/**\n * Returns opt if Some, otherwise computes a fallback Option.\n * @param opt - First Option\n * @param fn - Function to compute fallback\n * @returns opt if Some, fn() otherwise\n * @example\n * orElse(some(1), () => some(2)) // Some(1)\n * orElse(none, () => some(2)) // Some(2)\n */\nexport function orElse<T>(opt: Some<T>, fn: () => Option<T>): Some<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T> {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Returns Some if exactly one of the Options is Some.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns Some if exactly one is Some, None otherwise\n * @example\n * xor(some(1), none) // Some(1)\n * xor(none, some(2)) // Some(2)\n * xor(some(1), some(2)) // None\n * xor(none, none) // None\n */\nexport function xor<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n const a = isSome(opt);\n const b = isSome(optb);\n if (a !== b) return a ? opt : optb;\n return NONE;\n}\n\n/**\n * Returns optb if opt is Some, None otherwise.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns optb if opt is Some, None otherwise\n * @example\n * and(some(1), some(2)) // Some(2)\n * and(none, some(2)) // None\n */\nexport function and<U>(opt: None, optb: Option<U>): None;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U>;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U> {\n return isSome(opt) ? optb : NONE;\n}\n\n/**\n * Combines two Options into an Option of a tuple.\n * @param opt - First Option\n * @param other - Second Option\n * @returns Some([a, b]) if both are Some, None otherwise\n * @example\n * zip(some(1), some('a')) // Some([1, 'a'])\n * zip(some(1), none) // None\n */\nexport function zip<T, U>(opt: Option<T>, other: Option<U>): Option<[T, U]> {\n return isSome(opt) && isSome(other) ? ([opt, other] as Some<[T, U]>) : NONE;\n}\n\n/**\n * Splits an Option of a tuple into a tuple of Options.\n * @param opt - Option containing a tuple\n * @returns Tuple of Options\n * @example\n * unzip(some([1, 'a'])) // [Some(1), Some('a')]\n * unzip(none) // [None, None]\n */\nexport function unzip<T, U>(opt: Option<[T, U]>): [Option<T>, Option<U>] {\n if (isNone(opt)) return [NONE, NONE];\n const [a, b] = opt;\n return [of(a), of(b)];\n}\n\n/**\n * Maps the value and returns it, or returns a default.\n * @param opt - The Option to map\n * @param defaultValue - Value if None\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultValue otherwise\n * @example\n * mapOr(some(2), 0, x => x * 2) // 4\n * mapOr(none, 0, x => x * 2) // 0\n */\nexport function mapOr<T, U>(opt: Option<T>, defaultValue: U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultValue;\n}\n\n/**\n * Maps the value and returns it, or computes a default.\n * @param opt - The Option to map\n * @param defaultFn - Function to compute default\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultFn() otherwise\n * @example\n * mapOrElse(some(2), () => 0, x => x * 2) // 4\n * mapOrElse(none, () => 0, x => x * 2) // 0\n */\nexport function mapOrElse<T, U>(opt: Option<T>, defaultFn: () => U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultFn();\n}\n\n/**\n * Flattens a nested Option.\n * @param opt - Option containing an Option\n * @returns The inner Option\n * @example\n * flatten(some(some(42))) // Some(42)\n * flatten(some(none)) // None\n * flatten(none) // None\n */\nexport function flatten<T>(opt: Option<Option<T>>): Option<T> {\n return isNone(opt) ? NONE : (opt as Option<T>);\n}\n\n/**\n * Checks if the Option contains a specific value (using ===).\n * @param opt - The Option to check\n * @param value - The value to compare\n * @returns true if Some and value matches\n * @example\n * contains(some(42), 42) // true\n * contains(some(42), 0) // false\n * contains(none, 42) // false\n */\nexport function contains<T>(opt: Option<T>, value: T): boolean {\n return isSome(opt) && opt === value;\n}\n\n/**\n * Checks if Some and the value satisfies a predicate.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if Some and predicate returns true\n * @example\n * isSomeAnd(some(4), x => x > 2) // true\n * isSomeAnd(some(1), x => x > 2) // false\n * isSomeAnd(none, x => x > 2) // false\n */\nexport function isSomeAnd<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isSome(opt) && predicate(opt);\n}\n\n/**\n * Converts an Option to an array.\n * @param opt - The Option to convert\n * @returns [value] if Some, [] if None\n * @example\n * toArray(some(42)) // [42]\n * toArray(none) // []\n */\nexport function toArray<T>(opt: Option<T>): readonly T[] {\n return isSome(opt) ? [opt] : (EMPTY as readonly T[]);\n}\n\n/**\n * Converts an Option to a nullable value.\n * @param opt - The Option to convert\n * @returns The value if Some, null if None\n * @example\n * toNullable(some(42)) // 42\n * toNullable(none) // null\n */\nexport function toNullable<T>(opt: Option<T>): T | null {\n return isSome(opt) ? opt : null;\n}\n\n/**\n * Converts an Option to an undefined-able value.\n * @param opt - The Option to convert\n * @returns The value if Some, undefined if None\n * @example\n * toUndefined(some(42)) // 42\n * toUndefined(none) // undefined\n */\nexport function toUndefined<T>(opt: Option<T>): T | undefined {\n return isSome(opt) ? opt : undefined;\n}\n\n/**\n * Pattern matches on an Option, handling both Some and None cases.\n * @param opt - The Option to match\n * @param onSome - Handler for Some case\n * @param onNone - Handler for None case\n * @returns Result of the matching handler\n * @example\n * match(some(42), x => x * 2, () => 0) // 84\n * match(none, x => x * 2, () => 0) // 0\n */\nexport function match<T, U>(opt: Option<T>, onSome: (value: T) => U, onNone: () => U): U {\n return isSome(opt) ? onSome(opt) : onNone();\n}\n\n/**\n * Converts an Option to a Result, using a provided error if None.\n * @param opt - The Option to convert\n * @param error - Error value if None\n * @returns Ok(value) if Some, Err(error) if None\n * @example\n * okOr(some(42), 'missing') // Ok(42)\n * okOr(none, 'missing') // Err('missing')\n */\nexport function okOr<T, E>(opt: Option<T>, error: E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(error);\n}\n\n/**\n * Converts an Option to a Result, computing the error if None.\n * @param opt - The Option to convert\n * @param fn - Function to compute error\n * @returns Ok(value) if Some, Err(fn()) if None\n * @example\n * okOrElse(some(42), () => 'missing') // Ok(42)\n * okOrElse(none, () => 'missing') // Err('missing')\n */\nexport function okOrElse<T, E>(opt: Option<T>, fn: () => E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(fn());\n}\n\n/**\n * Extracts the Ok value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(value) if Ok, None if Err\n * @example\n * ofOk(ok(42)) // Some(42)\n * ofOk(err('failed')) // None\n */\nexport function ofOk<T, E>(result: Result<T, E>): Option<T> {\n if (!isOk(result) || !isSome(result)) {\n return NONE;\n }\n return result as Some<T>;\n}\n\n/**\n * Extracts the Err value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(error) if Err, None if Ok\n * @example\n * ofErr(err('failed')) // Some('failed')\n * ofErr(ok(42)) // None\n */\nexport function ofErr<T, E>(result: Result<T, E>): Option<E> {\n if (!isErr(result)) {\n return NONE;\n }\n const error = (result as { error: E }).error;\n if (!isSome(error)) {\n return NONE;\n }\n return error as Some<E>;\n}\n"],"names":["and","andThen","assertSome","contains","expect","filter","filterMap","findMap","flatMap","flatten","fromNullable","fromPromise","isNone","isNoneOr","isSome","isSomeAnd","map","mapOr","mapOrElse","match","of","ofErr","ofOk","okOr","okOrElse","or","orElse","satisfiesOption","tap","toArray","toNullable","toUndefined","unwrap","unwrapOr","unwrapOrElse","unwrapOrReturn","unzip","xor","zip","value","promise","onRejected","error","NONE","opt","onNone","message","Error","_","values","fn","collected","mapped","push","result","undefined","predicate","defaultValue","optb","a","b","other","defaultFn","EMPTY","onSome","err","isOk","isErr"],"mappings":";;;;;;;;;;;QA2UgBA;eAAAA;;QAzKAC;eAAAA;;QAlGAC;eAAAA;;QA6VAC;eAAAA;;QApJAC;eAAAA;;QAxDAC;eAAAA;;QAlHAC;eAAAA;;QAkBAC;eAAAA;;QAqCAC;eAAAA;;QAyPAC;eAAAA;;QA9XAC;eAAAA;;QAaMC;eAAAA;;QA1BLC;eAAAA,gBAAM;;QA8LPC;eAAAA;;QA9LPC;eAAAA,gBAAM;;QAuaCC;eAAAA;;QAvSAC;eAAAA;;QAgPAC;eAAAA;;QAcAC;eAAAA;;QA2FAC;eAAAA;;QAzdSC;eAAAA,kBAAE;;QA8gBXC;eAAAA;;QAfAC;eAAA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ACA,OAAOD;AACT"}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts"],"sourcesContent":["import { NONE, EMPTY, isSome, isNone, optionOf as of, err, isOk, isErr } from './types.js';\nimport type { Some, None, Option, NoneValueType, ValueType, Result, Ok, Widen } from './types.js';\n\nexport type { Some, None, Option };\nexport { isSome, isNone, of };\n\nconst NONE_PAIR: readonly [None, None] = Object.freeze([NONE, NONE]);\n\n/**\n * Creates an Option from a nullable value with widened types.\n * @param value - The value to wrap\n * @returns Some(value) if non-null, None otherwise\n * @example\n * fromNullable(42) // Some(42) with type Option<number>\n * fromNullable(null) // None\n */\nexport function fromNullable(value: null): None;\nexport function fromNullable(value: undefined): None;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>>;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>> {\n return of(value) as Option<Widen<T>>;\n}\n\n/**\n * Creates an Option from a Promise. Resolves to Some if successful, None on rejection.\n * @param promise - The promise to convert\n * @param onRejected - Optional handler for rejected promises\n * @returns Promise resolving to Some(value) or None\n * @example\n * await fromPromise(Promise.resolve(42)) // Some(42)\n * await fromPromise(Promise.reject('error')) // None\n */\nexport async function fromPromise<T>(promise: Promise<T | NoneValueType>, onRejected?: (error: unknown) => T | NoneValueType): Promise<Option<T>> {\n try {\n const value = await promise;\n return of(value as T);\n } catch (error) {\n if (!onRejected) {\n return NONE;\n }\n return of(onRejected(error));\n }\n}\n\n/**\n * Unwraps an Option or returns a computed value if None.\n * @param opt - The Option to unwrap\n * @param onNone - Function called if opt is None\n * @returns The value if Some, or the result of onNone()\n * @example\n * unwrapOrReturn(some(42), () => 0) // 42\n * unwrapOrReturn(none, () => 0) // 0\n */\nexport function unwrapOrReturn<T, R>(opt: Option<T>, onNone: () => R): Widen<T> | R {\n return isSome(opt) ? (opt as Widen<T>) : onNone();\n}\n\n/**\n * Asserts that an Option is Some, throwing if None.\n * @param opt - The Option to assert\n * @param message - Custom error message\n * @throws Error if opt is None\n * @example\n * assertSome(some(42)) // passes\n * assertSome(none) // throws Error\n */\nexport function assertSome<T>(opt: Option<T>, message?: string): asserts opt is Some<ValueType<T>> {\n if (isNone(opt)) {\n throw new Error(message ?? 'Expected Option to contain a value');\n }\n}\n\n/**\n * Compile-time type assertion helper to satisfy Option type constraints.\n *\n * WARNING: This function performs NO runtime validation. It is a no-op at\n * runtime to preserve zero-allocation semantics. Use assertSome() if you\n * need runtime validation that a value is Some.\n *\n * @param _ - The value to assert as Option (not validated at runtime)\n * @example\n * const value: number | null = getValue();\n * satisfiesOption(value); // Compiles, but no runtime check\n * // value is now typed as Option<number>\n */\nexport function satisfiesOption<T>(_: Option<T> | T): asserts _ is Option<T> {\n // Compile-time only - no runtime validation to preserve zero-allocation semantics.\n}\n\n/**\n * Maps and filters an iterable, collecting only Some values.\n * @param values - The iterable to process\n * @param fn - Function that returns Option for each value\n * @returns Array of unwrapped Some values\n * @example\n * filterMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // [4, 6]\n */\nexport function filterMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): U[] {\n const collected: U[] = [];\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) collected.push(mapped);\n }\n return collected;\n}\n\n/**\n * Finds the first element that maps to Some, returning that value.\n * @param values - Iterable to search\n * @param fn - Function that returns Some for matches\n * @returns The first Some value, or None if no match\n * @example\n * findMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // Some(4)\n * findMap([1], n => n > 5 ? some(n) : none) // None\n */\nexport function findMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): Option<U> {\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) return mapped;\n }\n return NONE;\n}\n\n/**\n * Transforms the value inside a Some, or returns None.\n * @param opt - The Option to map\n * @param fn - Transform function\n * @returns Some(fn(value)) if Some, None otherwise\n * @example\n * map(some(2), x => x * 2) // Some(4)\n * map(none, x => x * 2) // None\n */\nexport function map<T, U>(opt: None, fn: (value: T) => U): None;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U>;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U> {\n if (isNone(opt)) return NONE;\n const result = fn(opt);\n return result === null || result === undefined ? NONE : (result as Some<ValueType<U>>);\n}\n\n/**\n * Chains Option-returning functions. Returns None if the input is None.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n * @example\n * flatMap(some(2), x => some(x * 2)) // Some(4)\n * flatMap(some(2), x => none) // None\n * flatMap(none, x => some(x * 2)) // None\n */\nexport function flatMap<T, U>(opt: None, fn: (value: T) => Option<U>): None;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U>;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U> {\n return isNone(opt) ? NONE : fn(opt);\n}\n\n/**\n * Alias for flatMap. Chains Option-returning functions.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n */\nexport const andThen: typeof flatMap = flatMap;\n\n/**\n * Executes a side effect if Some, then returns the original Option.\n * @param opt - The Option to tap\n * @param fn - Side effect function\n * @returns The original Option unchanged\n * @example\n * tap(some(42), x => console.log(x)) // logs 42, returns Some(42)\n */\nexport function tap<T>(opt: None, fn: (value: T) => void): None;\nexport function tap<T>(opt: Some<T>, fn: (value: T) => void): Some<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T> {\n if (isSome(opt)) {\n fn(opt);\n }\n return opt;\n}\n\n/**\n * Executes a side effect if None, then returns the original Option.\n * @param opt - The Option to tap\n * @param fn - Side effect function\n * @returns The original Option unchanged\n * @example\n * tapNone(none, () => console.log('missing')) // logs 'missing', returns None\n */\nexport function tapNone<T>(opt: Some<T>, fn: () => void): Some<T>;\nexport function tapNone(opt: None, fn: () => void): None;\nexport function tapNone<T>(opt: Option<T>, fn: () => void): Option<T>;\nexport function tapNone<T>(opt: Option<T>, fn: () => void): Option<T> {\n if (isNone(opt)) {\n fn();\n }\n return opt;\n}\n\n/**\n * Returns true if None, or if Some and predicate returns true.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if None or predicate(value) is true\n * @example\n * isNoneOr(none, x => x > 2) // true\n * isNoneOr(some(4), x => x > 2) // true\n * isNoneOr(some(1), x => x > 2) // false\n */\nexport function isNoneOr<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isNone(opt) || predicate(opt);\n}\n\n/**\n * Returns Some if the value passes the predicate, None otherwise.\n * @param opt - The Option to filter\n * @param predicate - Test function\n * @returns Some if predicate returns true, None otherwise\n * @example\n * filter(some(4), x => x > 2) // Some(4)\n * filter(some(1), x => x > 2) // None\n */\nexport function filter<T>(opt: None, predicate: (value: T) => boolean): None;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T>;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T> {\n return isSome(opt) && predicate(opt) ? opt : NONE;\n}\n\n/**\n * Extracts the value from Some, throws if None.\n * @param opt - The Option to unwrap\n * @returns The contained value\n * @throws Error if opt is None\n * @example\n * unwrap(some(42)) // 42\n * unwrap(none) // throws Error\n */\nexport function unwrap<T>(opt: Option<T>): T {\n if (isNone(opt)) {\n throw new Error('Called unwrap on None');\n }\n return opt;\n}\n\n/**\n * Extracts the value from Some, or returns a default value.\n * @param opt - The Option to unwrap\n * @param defaultValue - Value to return if None\n * @returns The contained value or defaultValue\n * @example\n * unwrapOr(some(42), 0) // 42\n * unwrapOr(none, 0) // 0\n */\nexport function unwrapOr<T>(opt: Option<T>, defaultValue: T): T {\n return isSome(opt) ? opt : defaultValue;\n}\n\n/**\n * Extracts the value from Some, or computes a default.\n * @param opt - The Option to unwrap\n * @param fn - Function to compute default value\n * @returns The contained value or fn()\n * @example\n * unwrapOrElse(some(42), () => 0) // 42\n * unwrapOrElse(none, () => 0) // 0\n */\nexport function unwrapOrElse<T>(opt: Option<T>, fn: () => T): T {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Extracts the value from Some, throws with custom message if None.\n * @param opt - The Option to unwrap\n * @param message - Error message if None\n * @returns The contained value\n * @throws Error with message if opt is None\n * @example\n * expect(some(42), 'missing value') // 42\n * expect(none, 'missing value') // throws Error('missing value')\n */\nexport function expect<T>(opt: Option<T>, message: string): T {\n if (isNone(opt)) {\n throw new Error(message);\n }\n return opt;\n}\n\n/**\n * Returns the first Some, or the second Option if the first is None.\n * @param opt - First Option\n * @param optb - Fallback Option\n * @returns opt if Some, optb otherwise\n * @example\n * or(some(1), some(2)) // Some(1)\n * or(none, some(2)) // Some(2)\n */\nexport function or<T>(opt: Some<T>, optb: Option<T>): Some<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n return isSome(opt) ? opt : optb;\n}\n\n/**\n * Returns opt if Some, otherwise computes a fallback Option.\n * @param opt - First Option\n * @param fn - Function to compute fallback\n * @returns opt if Some, fn() otherwise\n * @example\n * orElse(some(1), () => some(2)) // Some(1)\n * orElse(none, () => some(2)) // Some(2)\n */\nexport function orElse<T>(opt: Some<T>, fn: () => Option<T>): Some<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T> {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Returns Some if exactly one of the Options is Some.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns Some if exactly one is Some, None otherwise\n * @example\n * xor(some(1), none) // Some(1)\n * xor(none, some(2)) // Some(2)\n * xor(some(1), some(2)) // None\n * xor(none, none) // None\n */\nexport function xor<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n const a = isSome(opt);\n const b = isSome(optb);\n if (a !== b) return a ? opt : optb;\n return NONE;\n}\n\n/**\n * Returns optb if opt is Some, None otherwise.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns optb if opt is Some, None otherwise\n * @example\n * and(some(1), some(2)) // Some(2)\n * and(none, some(2)) // None\n */\nexport function and<U>(opt: None, optb: Option<U>): None;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U>;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U> {\n return isSome(opt) ? optb : NONE;\n}\n\n/**\n * Combines two Options into an Option of a tuple.\n * @param opt - First Option\n * @param other - Second Option\n * @returns Some([a, b]) if both are Some, None otherwise\n * @example\n * zip(some(1), some('a')) // Some([1, 'a'])\n * zip(some(1), none) // None\n */\nexport function zip<T, U>(opt: Option<T>, other: Option<U>): Option<[T, U]> {\n return isSome(opt) && isSome(other) ? ([opt, other] as Some<[T, U]>) : NONE;\n}\n\n/**\n * Splits an Option of a tuple into a tuple of Options.\n * @param opt - Option containing a tuple\n * @returns Tuple of Options\n * @example\n * unzip(some([1, 'a'])) // [Some(1), Some('a')]\n * unzip(none) // [None, None]\n */\nexport function unzip<T, U>(opt: Option<[T, U]>): [Option<T>, Option<U>] {\n if (isNone(opt)) return NONE_PAIR as [Option<T>, Option<U>];\n const [a, b] = opt;\n return [of(a), of(b)];\n}\n\n/**\n * Maps the value and returns it, or returns a default.\n * @param opt - The Option to map\n * @param defaultValue - Value if None\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultValue otherwise\n * @example\n * mapOr(some(2), 0, x => x * 2) // 4\n * mapOr(none, 0, x => x * 2) // 0\n */\nexport function mapOr<T, U>(opt: Option<T>, defaultValue: U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultValue;\n}\n\n/**\n * Maps the value and returns it, or computes a default.\n * @param opt - The Option to map\n * @param defaultFn - Function to compute default\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultFn() otherwise\n * @example\n * mapOrElse(some(2), () => 0, x => x * 2) // 4\n * mapOrElse(none, () => 0, x => x * 2) // 0\n */\nexport function mapOrElse<T, U>(opt: Option<T>, defaultFn: () => U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultFn();\n}\n\n/**\n * Flattens a nested Option.\n * @param opt - Option containing an Option\n * @returns The inner Option\n * @example\n * flatten(some(some(42))) // Some(42)\n * flatten(some(none)) // None\n * flatten(none) // None\n */\nexport function flatten<T>(opt: Option<Option<T>>): Option<T> {\n return isNone(opt) ? NONE : (opt as Option<T>);\n}\n\n/**\n * Checks if the Option contains a specific value (using ===).\n * @param opt - The Option to check\n * @param value - The value to compare\n * @returns true if Some and value matches\n * @example\n * contains(some(42), 42) // true\n * contains(some(42), 0) // false\n * contains(none, 42) // false\n */\nexport function contains<T>(opt: Option<T>, value: T): boolean {\n return isSome(opt) && (opt === value || (opt !== opt && value !== value));\n}\n\n/**\n * Checks if Some and the value satisfies a predicate.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if Some and predicate returns true\n * @example\n * isSomeAnd(some(4), x => x > 2) // true\n * isSomeAnd(some(1), x => x > 2) // false\n * isSomeAnd(none, x => x > 2) // false\n */\nexport function isSomeAnd<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isSome(opt) && predicate(opt);\n}\n\n/**\n * Converts an Option to an array.\n * @param opt - The Option to convert\n * @returns [value] if Some, [] if None\n * @example\n * toArray(some(42)) // [42]\n * toArray(none) // []\n */\nexport function toArray<T>(opt: Option<T>): readonly T[] {\n return isSome(opt) ? [opt] : (EMPTY as readonly T[]);\n}\n\n/**\n * Converts an Option to a nullable value.\n * @param opt - The Option to convert\n * @returns The value if Some, null if None\n * @example\n * toNullable(some(42)) // 42\n * toNullable(none) // null\n */\nexport function toNullable<T>(opt: Option<T>): T | null {\n return isSome(opt) ? opt : null;\n}\n\n/**\n * Converts an Option to an undefined-able value.\n * @param opt - The Option to convert\n * @returns The value if Some, undefined if None\n * @example\n * toUndefined(some(42)) // 42\n * toUndefined(none) // undefined\n */\nexport function toUndefined<T>(opt: Option<T>): T | undefined {\n return isSome(opt) ? opt : undefined;\n}\n\n/**\n * Pattern matches on an Option, handling both Some and None cases.\n * @param opt - The Option to match\n * @param onSome - Handler for Some case\n * @param onNone - Handler for None case\n * @returns Result of the matching handler\n * @example\n * match(some(42), x => x * 2, () => 0) // 84\n * match(none, x => x * 2, () => 0) // 0\n */\nexport function match<T, U>(opt: Option<T>, onSome: (value: T) => U, onNone: () => U): U {\n return isSome(opt) ? onSome(opt) : onNone();\n}\n\n/**\n * Converts an Option to a Result, using a provided error if None.\n * @param opt - The Option to convert\n * @param error - Error value if None\n * @returns Ok(value) if Some, Err(error) if None\n * @example\n * okOr(some(42), 'missing') // Ok(42)\n * okOr(none, 'missing') // Err('missing')\n */\nexport function okOr<T, E>(opt: Option<T>, error: E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(error);\n}\n\n/**\n * Converts an Option to a Result, computing the error if None.\n * @param opt - The Option to convert\n * @param fn - Function to compute error\n * @returns Ok(value) if Some, Err(fn()) if None\n * @example\n * okOrElse(some(42), () => 'missing') // Ok(42)\n * okOrElse(none, () => 'missing') // Err('missing')\n */\nexport function okOrElse<T, E>(opt: Option<T>, fn: () => E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(fn());\n}\n\n/**\n * Extracts the Ok value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(value) if Ok, None if Err\n * @example\n * ofOk(ok(42)) // Some(42)\n * ofOk(err('failed')) // None\n */\nexport function ofOk<T, E>(result: Result<T, E>): Option<T> {\n if (!isOk(result) || !isSome(result)) {\n return NONE;\n }\n return result as Some<T>;\n}\n\n/**\n * Extracts the Err value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(error) if Err, None if Ok\n * @example\n * ofErr(err('failed')) // Some('failed')\n * ofErr(ok(42)) // None\n */\nexport function ofErr<T, E>(result: Result<T, E>): Option<E> {\n if (!isErr(result)) {\n return NONE;\n }\n const error = (result as { error: E }).error;\n if (!isSome(error)) {\n return NONE;\n }\n return error as Some<E>;\n}\n"],"names":["and","andThen","assertSome","contains","expect","filter","filterMap","findMap","flatMap","flatten","fromNullable","fromPromise","isNone","isNoneOr","isSome","isSomeAnd","map","mapOr","mapOrElse","match","of","ofErr","ofOk","okOr","okOrElse","or","orElse","satisfiesOption","tap","tapNone","toArray","toNullable","toUndefined","unwrap","unwrapOr","unwrapOrElse","unwrapOrReturn","unzip","xor","zip","NONE_PAIR","Object","freeze","NONE","value","promise","onRejected","error","opt","onNone","message","Error","_","values","fn","collected","mapped","push","result","undefined","predicate","defaultValue","optb","a","b","other","defaultFn","EMPTY","onSome","err","isOk","isErr"],"mappings":";;;;;;;;;;;QA2VgBA;eAAAA;;QAzLHC;eAAAA;;QAhGGC;eAAAA;;QA2WAC;eAAAA;;QApJAC;eAAAA;;QAxDAC;eAAAA;;QAhIAC;eAAAA;;QAkBAC;eAAAA;;QAqCAC;eAAAA;;QAuQAC;eAAAA;;QA5YAC;eAAAA;;QAaMC;eAAAA;;QA5BLC;eAAAA,gBAAM;;QA8MPC;eAAAA;;QA9MPC;eAAAA,gBAAM;;QAubCC;eAAAA;;QArTAC;eAAAA;;QA8PAC;eAAAA;;QAcAC;eAAAA;;QA2FAC;eAAAA;;QAzeSC;eAAAA,kBAAE;;QA8hBXC;eAAAA;;QAfAC;eAAAA;;QAzBAC;eAAAA;;QAaAC;eAAAA;;QA5NAC;eAAAA;;QAeAC;eAAAA;;QArOAC;eAAAA;;QA0FAC;eAAAA;;QAkBAC;eAAAA;;QAsQAC;eAAAA;;QAYAC;eAAAA;;QAYAC;eAAAA;;QAjPAC;eAAAA;;QAgBAC;eAAAA;;QAaAC;eAAAA;;QAtNAC;eAAAA;;QA+TAC;eAAAA;;QA3CAC;eAAAA;;QA+BAC;eAAAA;;;0BAxW8D;AAM9E,MAAMC,YAAmCC,OAAOC,MAAM,CAAC;IAACC,cAAI;IAAEA,cAAI;CAAC;AAa5D,SAASjC,aAAgBkC,KAAwB;IACtD,OAAOxB,IAAAA,kBAAE,EAACwB;AACZ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,SAASpC,WAAciB,GAAc;IAC1C,OAAOlC,IAAAA,gBAAM,EAACkC,OAAOA,MAAM;AAC7B;AAUO,SAAShB,YAAegB,GAAc;IAC3C,OAAOlC,IAAAA,gBAAM,EAACkC,OAAOA,MAAMW;AAC7B;AAYO,SAASxC,MAAY6B,GAAc,EAAEoB,MAAuB,EAAEnB,MAAe;IAClF,OAAOnC,IAAAA,gBAAM,EAACkC,OAAOoB,OAAOpB,OAAOC;AACrC;AAWO,SAAS1B,KAAWyB,GAAc,EAAED,KAAQ;IACjD,OAAOjC,IAAAA,gBAAM,EAACkC,OAAQA,MAA2BqB,IAAAA,aAAG,EAACtB;AACvD;AAWO,SAASvB,SAAewB,GAAc,EAAEM,EAAW;IACxD,OAAOxC,IAAAA,gBAAM,EAACkC,OAAQA,MAA2BqB,IAAAA,aAAG,EAACf;AACvD;AAUO,SAAShC,KAAWoC,MAAoB;IAC7C,IAAI,CAACY,IAAAA,cAAI,EAACZ,WAAW,CAAC5C,IAAAA,gBAAM,EAAC4C,SAAS;QACpC,OAAOf,cAAI;IACb;IACA,OAAOe;AACT;AAUO,SAASrC,MAAYqC,MAAoB;IAC9C,IAAI,CAACa,IAAAA,eAAK,EAACb,SAAS;QAClB,OAAOf,cAAI;IACb;IACA,MAAMI,QAAQ,AAACW,OAAwBX,KAAK;IAC5C,IAAI,CAACjC,IAAAA,gBAAM,EAACiC,QAAQ;QAClB,OAAOJ,cAAI;IACb;IACA,OAAOI;AACT"}
|
package/build/option.d.ts
CHANGED
|
@@ -105,8 +105,7 @@ export declare function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U
|
|
|
105
105
|
* @param fn - Function returning an Option
|
|
106
106
|
* @returns The result of fn(value) if Some, None otherwise
|
|
107
107
|
*/
|
|
108
|
-
export declare
|
|
109
|
-
export declare function andThen<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U>;
|
|
108
|
+
export declare const andThen: typeof flatMap;
|
|
110
109
|
/**
|
|
111
110
|
* Executes a side effect if Some, then returns the original Option.
|
|
112
111
|
* @param opt - The Option to tap
|
|
@@ -118,6 +117,17 @@ export declare function andThen<T, U>(opt: Option<T>, fn: (value: T) => Option<U
|
|
|
118
117
|
export declare function tap<T>(opt: None, fn: (value: T) => void): None;
|
|
119
118
|
export declare function tap<T>(opt: Some<T>, fn: (value: T) => void): Some<T>;
|
|
120
119
|
export declare function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T>;
|
|
120
|
+
/**
|
|
121
|
+
* Executes a side effect if None, then returns the original Option.
|
|
122
|
+
* @param opt - The Option to tap
|
|
123
|
+
* @param fn - Side effect function
|
|
124
|
+
* @returns The original Option unchanged
|
|
125
|
+
* @example
|
|
126
|
+
* tapNone(none, () => console.log('missing')) // logs 'missing', returns None
|
|
127
|
+
*/
|
|
128
|
+
export declare function tapNone<T>(opt: Some<T>, fn: () => void): Some<T>;
|
|
129
|
+
export declare function tapNone(opt: None, fn: () => void): None;
|
|
130
|
+
export declare function tapNone<T>(opt: Option<T>, fn: () => void): Option<T>;
|
|
121
131
|
/**
|
|
122
132
|
* Returns true if None, or if Some and predicate returns true.
|
|
123
133
|
* @param opt - The Option to check
|
package/build/option.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { NONE, EMPTY, isSome, isNone, optionOf as of, err, isOk, isErr } from "./types.js";
|
|
2
2
|
export { isSome, isNone, of };
|
|
3
|
+
const NONE_PAIR = Object.freeze([
|
|
4
|
+
NONE,
|
|
5
|
+
NONE
|
|
6
|
+
]);
|
|
3
7
|
export function fromNullable(value) {
|
|
4
8
|
return of(value);
|
|
5
9
|
}
|
|
@@ -46,15 +50,19 @@ export function map(opt, fn) {
|
|
|
46
50
|
export function flatMap(opt, fn) {
|
|
47
51
|
return isNone(opt) ? NONE : fn(opt);
|
|
48
52
|
}
|
|
49
|
-
export
|
|
50
|
-
return isNone(opt) ? NONE : fn(opt);
|
|
51
|
-
}
|
|
53
|
+
export const andThen = flatMap;
|
|
52
54
|
export function tap(opt, fn) {
|
|
53
55
|
if (isSome(opt)) {
|
|
54
56
|
fn(opt);
|
|
55
57
|
}
|
|
56
58
|
return opt;
|
|
57
59
|
}
|
|
60
|
+
export function tapNone(opt, fn) {
|
|
61
|
+
if (isNone(opt)) {
|
|
62
|
+
fn();
|
|
63
|
+
}
|
|
64
|
+
return opt;
|
|
65
|
+
}
|
|
58
66
|
export function isNoneOr(opt, predicate) {
|
|
59
67
|
return isNone(opt) || predicate(opt);
|
|
60
68
|
}
|
|
@@ -101,10 +109,7 @@ export function zip(opt, other) {
|
|
|
101
109
|
] : NONE;
|
|
102
110
|
}
|
|
103
111
|
export function unzip(opt) {
|
|
104
|
-
if (isNone(opt)) return
|
|
105
|
-
NONE,
|
|
106
|
-
NONE
|
|
107
|
-
];
|
|
112
|
+
if (isNone(opt)) return NONE_PAIR;
|
|
108
113
|
const [a, b] = opt;
|
|
109
114
|
return [
|
|
110
115
|
of(a),
|
|
@@ -121,7 +126,7 @@ export function flatten(opt) {
|
|
|
121
126
|
return isNone(opt) ? NONE : opt;
|
|
122
127
|
}
|
|
123
128
|
export function contains(opt, value) {
|
|
124
|
-
return isSome(opt) && opt === value;
|
|
129
|
+
return isSome(opt) && (opt === value || opt !== opt && value !== value);
|
|
125
130
|
}
|
|
126
131
|
export function isSomeAnd(opt, predicate) {
|
|
127
132
|
return isSome(opt) && predicate(opt);
|
package/build/option.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts"],"sourcesContent":["import { NONE, EMPTY, isSome, isNone, optionOf as of, err, isOk, isErr } from './types.js';\nimport type { Some, None, Option, NoneValueType, ValueType, Result, Ok, Widen } from './types.js';\n\nexport type { Some, None, Option };\nexport { isSome, isNone, of };\n\n/**\n * Creates an Option from a nullable value with widened types.\n * @param value - The value to wrap\n * @returns Some(value) if non-null, None otherwise\n * @example\n * fromNullable(42) // Some(42) with type Option<number>\n * fromNullable(null) // None\n */\nexport function fromNullable(value: null): None;\nexport function fromNullable(value: undefined): None;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>>;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>> {\n return of(value) as Option<Widen<T>>;\n}\n\n/**\n * Creates an Option from a Promise. Resolves to Some if successful, None on rejection.\n * @param promise - The promise to convert\n * @param onRejected - Optional handler for rejected promises\n * @returns Promise resolving to Some(value) or None\n * @example\n * await fromPromise(Promise.resolve(42)) // Some(42)\n * await fromPromise(Promise.reject('error')) // None\n */\nexport async function fromPromise<T>(promise: Promise<T | NoneValueType>, onRejected?: (error: unknown) => T | NoneValueType): Promise<Option<T>> {\n try {\n const value = await promise;\n return of(value as T);\n } catch (error) {\n if (!onRejected) {\n return NONE;\n }\n return of(onRejected(error));\n }\n}\n\n/**\n * Unwraps an Option or returns a computed value if None.\n * @param opt - The Option to unwrap\n * @param onNone - Function called if opt is None\n * @returns The value if Some, or the result of onNone()\n * @example\n * unwrapOrReturn(some(42), () => 0) // 42\n * unwrapOrReturn(none, () => 0) // 0\n */\nexport function unwrapOrReturn<T, R>(opt: Option<T>, onNone: () => R): Widen<T> | R {\n return isSome(opt) ? (opt as Widen<T>) : onNone();\n}\n\n/**\n * Asserts that an Option is Some, throwing if None.\n * @param opt - The Option to assert\n * @param message - Custom error message\n * @throws Error if opt is None\n * @example\n * assertSome(some(42)) // passes\n * assertSome(none) // throws Error\n */\nexport function assertSome<T>(opt: Option<T>, message?: string): asserts opt is Some<ValueType<T>> {\n if (isNone(opt)) {\n throw new Error(message ?? 'Expected Option to contain a value');\n }\n}\n\n/**\n * Compile-time type assertion helper to satisfy Option type constraints.\n *\n * WARNING: This function performs NO runtime validation. It is a no-op at\n * runtime to preserve zero-allocation semantics. Use assertSome() if you\n * need runtime validation that a value is Some.\n *\n * @param _ - The value to assert as Option (not validated at runtime)\n * @example\n * const value: number | null = getValue();\n * satisfiesOption(value); // Compiles, but no runtime check\n * // value is now typed as Option<number>\n */\nexport function satisfiesOption<T>(_: Option<T> | T): asserts _ is Option<T> {\n // Compile-time only - no runtime validation to preserve zero-allocation semantics.\n}\n\n/**\n * Maps and filters an iterable, collecting only Some values.\n * @param values - The iterable to process\n * @param fn - Function that returns Option for each value\n * @returns Array of unwrapped Some values\n * @example\n * filterMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // [4, 6]\n */\nexport function filterMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): U[] {\n const collected: U[] = [];\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) collected.push(mapped);\n }\n return collected;\n}\n\n/**\n * Finds the first element that maps to Some, returning that value.\n * @param values - Iterable to search\n * @param fn - Function that returns Some for matches\n * @returns The first Some value, or None if no match\n * @example\n * findMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // Some(4)\n * findMap([1], n => n > 5 ? some(n) : none) // None\n */\nexport function findMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): Option<U> {\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) return mapped;\n }\n return NONE;\n}\n\n/**\n * Transforms the value inside a Some, or returns None.\n * @param opt - The Option to map\n * @param fn - Transform function\n * @returns Some(fn(value)) if Some, None otherwise\n * @example\n * map(some(2), x => x * 2) // Some(4)\n * map(none, x => x * 2) // None\n */\nexport function map<T, U>(opt: None, fn: (value: T) => U): None;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U>;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U> {\n if (isNone(opt)) return NONE;\n const result = fn(opt);\n return result === null || result === undefined ? NONE : (result as Some<ValueType<U>>);\n}\n\n/**\n * Chains Option-returning functions. Returns None if the input is None.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n * @example\n * flatMap(some(2), x => some(x * 2)) // Some(4)\n * flatMap(some(2), x => none) // None\n * flatMap(none, x => some(x * 2)) // None\n */\nexport function flatMap<T, U>(opt: None, fn: (value: T) => Option<U>): None;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U>;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U> {\n return isNone(opt) ? NONE : fn(opt);\n}\n\n/**\n * Alias for flatMap. Chains Option-returning functions.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n */\nexport function andThen<T, U>(opt: None, fn: (value: T) => Option<U>): None;\nexport function andThen<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U>;\nexport function andThen<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U> {\n return isNone(opt) ? NONE : fn(opt);\n}\n\n/**\n * Executes a side effect if Some, then returns the original Option.\n * @param opt - The Option to tap\n * @param fn - Side effect function\n * @returns The original Option unchanged\n * @example\n * tap(some(42), x => console.log(x)) // logs 42, returns Some(42)\n */\nexport function tap<T>(opt: None, fn: (value: T) => void): None;\nexport function tap<T>(opt: Some<T>, fn: (value: T) => void): Some<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T> {\n if (isSome(opt)) {\n fn(opt);\n }\n return opt;\n}\n\n/**\n * Returns true if None, or if Some and predicate returns true.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if None or predicate(value) is true\n * @example\n * isNoneOr(none, x => x > 2) // true\n * isNoneOr(some(4), x => x > 2) // true\n * isNoneOr(some(1), x => x > 2) // false\n */\nexport function isNoneOr<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isNone(opt) || predicate(opt);\n}\n\n/**\n * Returns Some if the value passes the predicate, None otherwise.\n * @param opt - The Option to filter\n * @param predicate - Test function\n * @returns Some if predicate returns true, None otherwise\n * @example\n * filter(some(4), x => x > 2) // Some(4)\n * filter(some(1), x => x > 2) // None\n */\nexport function filter<T>(opt: None, predicate: (value: T) => boolean): None;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T>;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T> {\n return isSome(opt) && predicate(opt) ? opt : NONE;\n}\n\n/**\n * Extracts the value from Some, throws if None.\n * @param opt - The Option to unwrap\n * @returns The contained value\n * @throws Error if opt is None\n * @example\n * unwrap(some(42)) // 42\n * unwrap(none) // throws Error\n */\nexport function unwrap<T>(opt: Option<T>): T {\n if (isNone(opt)) {\n throw new Error('Called unwrap on None');\n }\n return opt;\n}\n\n/**\n * Extracts the value from Some, or returns a default value.\n * @param opt - The Option to unwrap\n * @param defaultValue - Value to return if None\n * @returns The contained value or defaultValue\n * @example\n * unwrapOr(some(42), 0) // 42\n * unwrapOr(none, 0) // 0\n */\nexport function unwrapOr<T>(opt: Option<T>, defaultValue: T): T {\n return isSome(opt) ? opt : defaultValue;\n}\n\n/**\n * Extracts the value from Some, or computes a default.\n * @param opt - The Option to unwrap\n * @param fn - Function to compute default value\n * @returns The contained value or fn()\n * @example\n * unwrapOrElse(some(42), () => 0) // 42\n * unwrapOrElse(none, () => 0) // 0\n */\nexport function unwrapOrElse<T>(opt: Option<T>, fn: () => T): T {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Extracts the value from Some, throws with custom message if None.\n * @param opt - The Option to unwrap\n * @param message - Error message if None\n * @returns The contained value\n * @throws Error with message if opt is None\n * @example\n * expect(some(42), 'missing value') // 42\n * expect(none, 'missing value') // throws Error('missing value')\n */\nexport function expect<T>(opt: Option<T>, message: string): T {\n if (isNone(opt)) {\n throw new Error(message);\n }\n return opt;\n}\n\n/**\n * Returns the first Some, or the second Option if the first is None.\n * @param opt - First Option\n * @param optb - Fallback Option\n * @returns opt if Some, optb otherwise\n * @example\n * or(some(1), some(2)) // Some(1)\n * or(none, some(2)) // Some(2)\n */\nexport function or<T>(opt: Some<T>, optb: Option<T>): Some<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n return isSome(opt) ? opt : optb;\n}\n\n/**\n * Returns opt if Some, otherwise computes a fallback Option.\n * @param opt - First Option\n * @param fn - Function to compute fallback\n * @returns opt if Some, fn() otherwise\n * @example\n * orElse(some(1), () => some(2)) // Some(1)\n * orElse(none, () => some(2)) // Some(2)\n */\nexport function orElse<T>(opt: Some<T>, fn: () => Option<T>): Some<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T> {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Returns Some if exactly one of the Options is Some.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns Some if exactly one is Some, None otherwise\n * @example\n * xor(some(1), none) // Some(1)\n * xor(none, some(2)) // Some(2)\n * xor(some(1), some(2)) // None\n * xor(none, none) // None\n */\nexport function xor<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n const a = isSome(opt);\n const b = isSome(optb);\n if (a !== b) return a ? opt : optb;\n return NONE;\n}\n\n/**\n * Returns optb if opt is Some, None otherwise.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns optb if opt is Some, None otherwise\n * @example\n * and(some(1), some(2)) // Some(2)\n * and(none, some(2)) // None\n */\nexport function and<U>(opt: None, optb: Option<U>): None;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U>;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U> {\n return isSome(opt) ? optb : NONE;\n}\n\n/**\n * Combines two Options into an Option of a tuple.\n * @param opt - First Option\n * @param other - Second Option\n * @returns Some([a, b]) if both are Some, None otherwise\n * @example\n * zip(some(1), some('a')) // Some([1, 'a'])\n * zip(some(1), none) // None\n */\nexport function zip<T, U>(opt: Option<T>, other: Option<U>): Option<[T, U]> {\n return isSome(opt) && isSome(other) ? ([opt, other] as Some<[T, U]>) : NONE;\n}\n\n/**\n * Splits an Option of a tuple into a tuple of Options.\n * @param opt - Option containing a tuple\n * @returns Tuple of Options\n * @example\n * unzip(some([1, 'a'])) // [Some(1), Some('a')]\n * unzip(none) // [None, None]\n */\nexport function unzip<T, U>(opt: Option<[T, U]>): [Option<T>, Option<U>] {\n if (isNone(opt)) return [NONE, NONE];\n const [a, b] = opt;\n return [of(a), of(b)];\n}\n\n/**\n * Maps the value and returns it, or returns a default.\n * @param opt - The Option to map\n * @param defaultValue - Value if None\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultValue otherwise\n * @example\n * mapOr(some(2), 0, x => x * 2) // 4\n * mapOr(none, 0, x => x * 2) // 0\n */\nexport function mapOr<T, U>(opt: Option<T>, defaultValue: U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultValue;\n}\n\n/**\n * Maps the value and returns it, or computes a default.\n * @param opt - The Option to map\n * @param defaultFn - Function to compute default\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultFn() otherwise\n * @example\n * mapOrElse(some(2), () => 0, x => x * 2) // 4\n * mapOrElse(none, () => 0, x => x * 2) // 0\n */\nexport function mapOrElse<T, U>(opt: Option<T>, defaultFn: () => U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultFn();\n}\n\n/**\n * Flattens a nested Option.\n * @param opt - Option containing an Option\n * @returns The inner Option\n * @example\n * flatten(some(some(42))) // Some(42)\n * flatten(some(none)) // None\n * flatten(none) // None\n */\nexport function flatten<T>(opt: Option<Option<T>>): Option<T> {\n return isNone(opt) ? NONE : (opt as Option<T>);\n}\n\n/**\n * Checks if the Option contains a specific value (using ===).\n * @param opt - The Option to check\n * @param value - The value to compare\n * @returns true if Some and value matches\n * @example\n * contains(some(42), 42) // true\n * contains(some(42), 0) // false\n * contains(none, 42) // false\n */\nexport function contains<T>(opt: Option<T>, value: T): boolean {\n return isSome(opt) && opt === value;\n}\n\n/**\n * Checks if Some and the value satisfies a predicate.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if Some and predicate returns true\n * @example\n * isSomeAnd(some(4), x => x > 2) // true\n * isSomeAnd(some(1), x => x > 2) // false\n * isSomeAnd(none, x => x > 2) // false\n */\nexport function isSomeAnd<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isSome(opt) && predicate(opt);\n}\n\n/**\n * Converts an Option to an array.\n * @param opt - The Option to convert\n * @returns [value] if Some, [] if None\n * @example\n * toArray(some(42)) // [42]\n * toArray(none) // []\n */\nexport function toArray<T>(opt: Option<T>): readonly T[] {\n return isSome(opt) ? [opt] : (EMPTY as readonly T[]);\n}\n\n/**\n * Converts an Option to a nullable value.\n * @param opt - The Option to convert\n * @returns The value if Some, null if None\n * @example\n * toNullable(some(42)) // 42\n * toNullable(none) // null\n */\nexport function toNullable<T>(opt: Option<T>): T | null {\n return isSome(opt) ? opt : null;\n}\n\n/**\n * Converts an Option to an undefined-able value.\n * @param opt - The Option to convert\n * @returns The value if Some, undefined if None\n * @example\n * toUndefined(some(42)) // 42\n * toUndefined(none) // undefined\n */\nexport function toUndefined<T>(opt: Option<T>): T | undefined {\n return isSome(opt) ? opt : undefined;\n}\n\n/**\n * Pattern matches on an Option, handling both Some and None cases.\n * @param opt - The Option to match\n * @param onSome - Handler for Some case\n * @param onNone - Handler for None case\n * @returns Result of the matching handler\n * @example\n * match(some(42), x => x * 2, () => 0) // 84\n * match(none, x => x * 2, () => 0) // 0\n */\nexport function match<T, U>(opt: Option<T>, onSome: (value: T) => U, onNone: () => U): U {\n return isSome(opt) ? onSome(opt) : onNone();\n}\n\n/**\n * Converts an Option to a Result, using a provided error if None.\n * @param opt - The Option to convert\n * @param error - Error value if None\n * @returns Ok(value) if Some, Err(error) if None\n * @example\n * okOr(some(42), 'missing') // Ok(42)\n * okOr(none, 'missing') // Err('missing')\n */\nexport function okOr<T, E>(opt: Option<T>, error: E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(error);\n}\n\n/**\n * Converts an Option to a Result, computing the error if None.\n * @param opt - The Option to convert\n * @param fn - Function to compute error\n * @returns Ok(value) if Some, Err(fn()) if None\n * @example\n * okOrElse(some(42), () => 'missing') // Ok(42)\n * okOrElse(none, () => 'missing') // Err('missing')\n */\nexport function okOrElse<T, E>(opt: Option<T>, fn: () => E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(fn());\n}\n\n/**\n * Extracts the Ok value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(value) if Ok, None if Err\n * @example\n * ofOk(ok(42)) // Some(42)\n * ofOk(err('failed')) // None\n */\nexport function ofOk<T, E>(result: Result<T, E>): Option<T> {\n if (!isOk(result) || !isSome(result)) {\n return NONE;\n }\n return result as Some<T>;\n}\n\n/**\n * Extracts the Err value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(error) if Err, None if Ok\n * @example\n * ofErr(err('failed')) // Some('failed')\n * ofErr(ok(42)) // None\n */\nexport function ofErr<T, E>(result: Result<T, E>): Option<E> {\n if (!isErr(result)) {\n return NONE;\n }\n const error = (result as { error: E }).error;\n if (!isSome(error)) {\n return NONE;\n }\n return error as Some<E>;\n}\n"],"names":["NONE","EMPTY","isSome","isNone","optionOf","of","err","isOk","isErr","fromNullable","value","fromPromise","promise","onRejected","error","unwrapOrReturn","opt","onNone","assertSome","message","Error","satisfiesOption","_","filterMap","values","fn","collected","mapped","push","findMap","map","result","undefined","flatMap","andThen","tap","isNoneOr","predicate","filter","unwrap","unwrapOr","defaultValue","unwrapOrElse","expect","or","optb","orElse","xor","a","b","and","zip","other","unzip","mapOr","mapOrElse","defaultFn","flatten","contains","isSomeAnd","toArray","toNullable","toUndefined","match","onSome","okOr","okOrElse","ofOk","ofErr"],"mappings":"AAAA,SAASA,IAAI,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,YAAYC,EAAE,EAAEC,GAAG,EAAEC,IAAI,EAAEC,KAAK,QAAQ,aAAa;AAI3F,SAASN,MAAM,EAAEC,MAAM,EAAEE,EAAE,GAAG;AAa9B,OAAO,SAASI,aAAgBC,KAAwB;IACtD,OAAOL,GAAGK;AAC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;IACxD,OAAOvB,OAAOc,OAAQA,MAA2BV,IAAImB;AACvD;AAUA,OAAO,SAAS0C,KAAWpC,MAAoB;IAC7C,IAAI,CAACxB,KAAKwB,WAAW,CAAC7B,OAAO6B,SAAS;QACpC,OAAO/B;IACT;IACA,OAAO+B;AACT;AAUA,OAAO,SAASqC,MAAYrC,MAAoB;IAC9C,IAAI,CAACvB,MAAMuB,SAAS;QAClB,OAAO/B;IACT;IACA,MAAMc,QAAQ,AAACiB,OAAwBjB,KAAK;IAC5C,IAAI,CAACZ,OAAOY,QAAQ;QAClB,OAAOd;IACT;IACA,OAAOc;AACT"}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts"],"sourcesContent":["import { NONE, EMPTY, isSome, isNone, optionOf as of, err, isOk, isErr } from './types.js';\nimport type { Some, None, Option, NoneValueType, ValueType, Result, Ok, Widen } from './types.js';\n\nexport type { Some, None, Option };\nexport { isSome, isNone, of };\n\nconst NONE_PAIR: readonly [None, None] = Object.freeze([NONE, NONE]);\n\n/**\n * Creates an Option from a nullable value with widened types.\n * @param value - The value to wrap\n * @returns Some(value) if non-null, None otherwise\n * @example\n * fromNullable(42) // Some(42) with type Option<number>\n * fromNullable(null) // None\n */\nexport function fromNullable(value: null): None;\nexport function fromNullable(value: undefined): None;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>>;\nexport function fromNullable<T>(value: T | NoneValueType): Option<Widen<T>> {\n return of(value) as Option<Widen<T>>;\n}\n\n/**\n * Creates an Option from a Promise. Resolves to Some if successful, None on rejection.\n * @param promise - The promise to convert\n * @param onRejected - Optional handler for rejected promises\n * @returns Promise resolving to Some(value) or None\n * @example\n * await fromPromise(Promise.resolve(42)) // Some(42)\n * await fromPromise(Promise.reject('error')) // None\n */\nexport async function fromPromise<T>(promise: Promise<T | NoneValueType>, onRejected?: (error: unknown) => T | NoneValueType): Promise<Option<T>> {\n try {\n const value = await promise;\n return of(value as T);\n } catch (error) {\n if (!onRejected) {\n return NONE;\n }\n return of(onRejected(error));\n }\n}\n\n/**\n * Unwraps an Option or returns a computed value if None.\n * @param opt - The Option to unwrap\n * @param onNone - Function called if opt is None\n * @returns The value if Some, or the result of onNone()\n * @example\n * unwrapOrReturn(some(42), () => 0) // 42\n * unwrapOrReturn(none, () => 0) // 0\n */\nexport function unwrapOrReturn<T, R>(opt: Option<T>, onNone: () => R): Widen<T> | R {\n return isSome(opt) ? (opt as Widen<T>) : onNone();\n}\n\n/**\n * Asserts that an Option is Some, throwing if None.\n * @param opt - The Option to assert\n * @param message - Custom error message\n * @throws Error if opt is None\n * @example\n * assertSome(some(42)) // passes\n * assertSome(none) // throws Error\n */\nexport function assertSome<T>(opt: Option<T>, message?: string): asserts opt is Some<ValueType<T>> {\n if (isNone(opt)) {\n throw new Error(message ?? 'Expected Option to contain a value');\n }\n}\n\n/**\n * Compile-time type assertion helper to satisfy Option type constraints.\n *\n * WARNING: This function performs NO runtime validation. It is a no-op at\n * runtime to preserve zero-allocation semantics. Use assertSome() if you\n * need runtime validation that a value is Some.\n *\n * @param _ - The value to assert as Option (not validated at runtime)\n * @example\n * const value: number | null = getValue();\n * satisfiesOption(value); // Compiles, but no runtime check\n * // value is now typed as Option<number>\n */\nexport function satisfiesOption<T>(_: Option<T> | T): asserts _ is Option<T> {\n // Compile-time only - no runtime validation to preserve zero-allocation semantics.\n}\n\n/**\n * Maps and filters an iterable, collecting only Some values.\n * @param values - The iterable to process\n * @param fn - Function that returns Option for each value\n * @returns Array of unwrapped Some values\n * @example\n * filterMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // [4, 6]\n */\nexport function filterMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): U[] {\n const collected: U[] = [];\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) collected.push(mapped);\n }\n return collected;\n}\n\n/**\n * Finds the first element that maps to Some, returning that value.\n * @param values - Iterable to search\n * @param fn - Function that returns Some for matches\n * @returns The first Some value, or None if no match\n * @example\n * findMap([1, 2, 3], n => n > 1 ? some(n * 2) : none) // Some(4)\n * findMap([1], n => n > 5 ? some(n) : none) // None\n */\nexport function findMap<T, U>(values: Iterable<T>, fn: (value: T) => Option<U>): Option<U> {\n for (const value of values) {\n const mapped = fn(value);\n if (isSome(mapped)) return mapped;\n }\n return NONE;\n}\n\n/**\n * Transforms the value inside a Some, or returns None.\n * @param opt - The Option to map\n * @param fn - Transform function\n * @returns Some(fn(value)) if Some, None otherwise\n * @example\n * map(some(2), x => x * 2) // Some(4)\n * map(none, x => x * 2) // None\n */\nexport function map<T, U>(opt: None, fn: (value: T) => U): None;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U>;\nexport function map<T, U>(opt: Option<T>, fn: (value: T) => U | NoneValueType): Option<U> {\n if (isNone(opt)) return NONE;\n const result = fn(opt);\n return result === null || result === undefined ? NONE : (result as Some<ValueType<U>>);\n}\n\n/**\n * Chains Option-returning functions. Returns None if the input is None.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n * @example\n * flatMap(some(2), x => some(x * 2)) // Some(4)\n * flatMap(some(2), x => none) // None\n * flatMap(none, x => some(x * 2)) // None\n */\nexport function flatMap<T, U>(opt: None, fn: (value: T) => Option<U>): None;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U>;\nexport function flatMap<T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U> {\n return isNone(opt) ? NONE : fn(opt);\n}\n\n/**\n * Alias for flatMap. Chains Option-returning functions.\n * @param opt - The Option to chain\n * @param fn - Function returning an Option\n * @returns The result of fn(value) if Some, None otherwise\n */\nexport const andThen: typeof flatMap = flatMap;\n\n/**\n * Executes a side effect if Some, then returns the original Option.\n * @param opt - The Option to tap\n * @param fn - Side effect function\n * @returns The original Option unchanged\n * @example\n * tap(some(42), x => console.log(x)) // logs 42, returns Some(42)\n */\nexport function tap<T>(opt: None, fn: (value: T) => void): None;\nexport function tap<T>(opt: Some<T>, fn: (value: T) => void): Some<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T>;\nexport function tap<T>(opt: Option<T>, fn: (value: T) => void): Option<T> {\n if (isSome(opt)) {\n fn(opt);\n }\n return opt;\n}\n\n/**\n * Executes a side effect if None, then returns the original Option.\n * @param opt - The Option to tap\n * @param fn - Side effect function\n * @returns The original Option unchanged\n * @example\n * tapNone(none, () => console.log('missing')) // logs 'missing', returns None\n */\nexport function tapNone<T>(opt: Some<T>, fn: () => void): Some<T>;\nexport function tapNone(opt: None, fn: () => void): None;\nexport function tapNone<T>(opt: Option<T>, fn: () => void): Option<T>;\nexport function tapNone<T>(opt: Option<T>, fn: () => void): Option<T> {\n if (isNone(opt)) {\n fn();\n }\n return opt;\n}\n\n/**\n * Returns true if None, or if Some and predicate returns true.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if None or predicate(value) is true\n * @example\n * isNoneOr(none, x => x > 2) // true\n * isNoneOr(some(4), x => x > 2) // true\n * isNoneOr(some(1), x => x > 2) // false\n */\nexport function isNoneOr<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isNone(opt) || predicate(opt);\n}\n\n/**\n * Returns Some if the value passes the predicate, None otherwise.\n * @param opt - The Option to filter\n * @param predicate - Test function\n * @returns Some if predicate returns true, None otherwise\n * @example\n * filter(some(4), x => x > 2) // Some(4)\n * filter(some(1), x => x > 2) // None\n */\nexport function filter<T>(opt: None, predicate: (value: T) => boolean): None;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T>;\nexport function filter<T>(opt: Option<T>, predicate: (value: T) => boolean): Option<T> {\n return isSome(opt) && predicate(opt) ? opt : NONE;\n}\n\n/**\n * Extracts the value from Some, throws if None.\n * @param opt - The Option to unwrap\n * @returns The contained value\n * @throws Error if opt is None\n * @example\n * unwrap(some(42)) // 42\n * unwrap(none) // throws Error\n */\nexport function unwrap<T>(opt: Option<T>): T {\n if (isNone(opt)) {\n throw new Error('Called unwrap on None');\n }\n return opt;\n}\n\n/**\n * Extracts the value from Some, or returns a default value.\n * @param opt - The Option to unwrap\n * @param defaultValue - Value to return if None\n * @returns The contained value or defaultValue\n * @example\n * unwrapOr(some(42), 0) // 42\n * unwrapOr(none, 0) // 0\n */\nexport function unwrapOr<T>(opt: Option<T>, defaultValue: T): T {\n return isSome(opt) ? opt : defaultValue;\n}\n\n/**\n * Extracts the value from Some, or computes a default.\n * @param opt - The Option to unwrap\n * @param fn - Function to compute default value\n * @returns The contained value or fn()\n * @example\n * unwrapOrElse(some(42), () => 0) // 42\n * unwrapOrElse(none, () => 0) // 0\n */\nexport function unwrapOrElse<T>(opt: Option<T>, fn: () => T): T {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Extracts the value from Some, throws with custom message if None.\n * @param opt - The Option to unwrap\n * @param message - Error message if None\n * @returns The contained value\n * @throws Error with message if opt is None\n * @example\n * expect(some(42), 'missing value') // 42\n * expect(none, 'missing value') // throws Error('missing value')\n */\nexport function expect<T>(opt: Option<T>, message: string): T {\n if (isNone(opt)) {\n throw new Error(message);\n }\n return opt;\n}\n\n/**\n * Returns the first Some, or the second Option if the first is None.\n * @param opt - First Option\n * @param optb - Fallback Option\n * @returns opt if Some, optb otherwise\n * @example\n * or(some(1), some(2)) // Some(1)\n * or(none, some(2)) // Some(2)\n */\nexport function or<T>(opt: Some<T>, optb: Option<T>): Some<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T>;\nexport function or<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n return isSome(opt) ? opt : optb;\n}\n\n/**\n * Returns opt if Some, otherwise computes a fallback Option.\n * @param opt - First Option\n * @param fn - Function to compute fallback\n * @returns opt if Some, fn() otherwise\n * @example\n * orElse(some(1), () => some(2)) // Some(1)\n * orElse(none, () => some(2)) // Some(2)\n */\nexport function orElse<T>(opt: Some<T>, fn: () => Option<T>): Some<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T>;\nexport function orElse<T>(opt: Option<T>, fn: () => Option<T>): Option<T> {\n return isSome(opt) ? opt : fn();\n}\n\n/**\n * Returns Some if exactly one of the Options is Some.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns Some if exactly one is Some, None otherwise\n * @example\n * xor(some(1), none) // Some(1)\n * xor(none, some(2)) // Some(2)\n * xor(some(1), some(2)) // None\n * xor(none, none) // None\n */\nexport function xor<T>(opt: Option<T>, optb: Option<T>): Option<T> {\n const a = isSome(opt);\n const b = isSome(optb);\n if (a !== b) return a ? opt : optb;\n return NONE;\n}\n\n/**\n * Returns optb if opt is Some, None otherwise.\n * @param opt - First Option\n * @param optb - Second Option\n * @returns optb if opt is Some, None otherwise\n * @example\n * and(some(1), some(2)) // Some(2)\n * and(none, some(2)) // None\n */\nexport function and<U>(opt: None, optb: Option<U>): None;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U>;\nexport function and<T, U>(opt: Option<T>, optb: Option<U>): Option<U> {\n return isSome(opt) ? optb : NONE;\n}\n\n/**\n * Combines two Options into an Option of a tuple.\n * @param opt - First Option\n * @param other - Second Option\n * @returns Some([a, b]) if both are Some, None otherwise\n * @example\n * zip(some(1), some('a')) // Some([1, 'a'])\n * zip(some(1), none) // None\n */\nexport function zip<T, U>(opt: Option<T>, other: Option<U>): Option<[T, U]> {\n return isSome(opt) && isSome(other) ? ([opt, other] as Some<[T, U]>) : NONE;\n}\n\n/**\n * Splits an Option of a tuple into a tuple of Options.\n * @param opt - Option containing a tuple\n * @returns Tuple of Options\n * @example\n * unzip(some([1, 'a'])) // [Some(1), Some('a')]\n * unzip(none) // [None, None]\n */\nexport function unzip<T, U>(opt: Option<[T, U]>): [Option<T>, Option<U>] {\n if (isNone(opt)) return NONE_PAIR as [Option<T>, Option<U>];\n const [a, b] = opt;\n return [of(a), of(b)];\n}\n\n/**\n * Maps the value and returns it, or returns a default.\n * @param opt - The Option to map\n * @param defaultValue - Value if None\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultValue otherwise\n * @example\n * mapOr(some(2), 0, x => x * 2) // 4\n * mapOr(none, 0, x => x * 2) // 0\n */\nexport function mapOr<T, U>(opt: Option<T>, defaultValue: U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultValue;\n}\n\n/**\n * Maps the value and returns it, or computes a default.\n * @param opt - The Option to map\n * @param defaultFn - Function to compute default\n * @param fn - Transform function\n * @returns fn(value) if Some, defaultFn() otherwise\n * @example\n * mapOrElse(some(2), () => 0, x => x * 2) // 4\n * mapOrElse(none, () => 0, x => x * 2) // 0\n */\nexport function mapOrElse<T, U>(opt: Option<T>, defaultFn: () => U, fn: (value: T) => U): U {\n return isSome(opt) ? fn(opt) : defaultFn();\n}\n\n/**\n * Flattens a nested Option.\n * @param opt - Option containing an Option\n * @returns The inner Option\n * @example\n * flatten(some(some(42))) // Some(42)\n * flatten(some(none)) // None\n * flatten(none) // None\n */\nexport function flatten<T>(opt: Option<Option<T>>): Option<T> {\n return isNone(opt) ? NONE : (opt as Option<T>);\n}\n\n/**\n * Checks if the Option contains a specific value (using ===).\n * @param opt - The Option to check\n * @param value - The value to compare\n * @returns true if Some and value matches\n * @example\n * contains(some(42), 42) // true\n * contains(some(42), 0) // false\n * contains(none, 42) // false\n */\nexport function contains<T>(opt: Option<T>, value: T): boolean {\n return isSome(opt) && (opt === value || (opt !== opt && value !== value));\n}\n\n/**\n * Checks if Some and the value satisfies a predicate.\n * @param opt - The Option to check\n * @param predicate - Test function\n * @returns true if Some and predicate returns true\n * @example\n * isSomeAnd(some(4), x => x > 2) // true\n * isSomeAnd(some(1), x => x > 2) // false\n * isSomeAnd(none, x => x > 2) // false\n */\nexport function isSomeAnd<T>(opt: Option<T>, predicate: (value: T) => boolean): boolean {\n return isSome(opt) && predicate(opt);\n}\n\n/**\n * Converts an Option to an array.\n * @param opt - The Option to convert\n * @returns [value] if Some, [] if None\n * @example\n * toArray(some(42)) // [42]\n * toArray(none) // []\n */\nexport function toArray<T>(opt: Option<T>): readonly T[] {\n return isSome(opt) ? [opt] : (EMPTY as readonly T[]);\n}\n\n/**\n * Converts an Option to a nullable value.\n * @param opt - The Option to convert\n * @returns The value if Some, null if None\n * @example\n * toNullable(some(42)) // 42\n * toNullable(none) // null\n */\nexport function toNullable<T>(opt: Option<T>): T | null {\n return isSome(opt) ? opt : null;\n}\n\n/**\n * Converts an Option to an undefined-able value.\n * @param opt - The Option to convert\n * @returns The value if Some, undefined if None\n * @example\n * toUndefined(some(42)) // 42\n * toUndefined(none) // undefined\n */\nexport function toUndefined<T>(opt: Option<T>): T | undefined {\n return isSome(opt) ? opt : undefined;\n}\n\n/**\n * Pattern matches on an Option, handling both Some and None cases.\n * @param opt - The Option to match\n * @param onSome - Handler for Some case\n * @param onNone - Handler for None case\n * @returns Result of the matching handler\n * @example\n * match(some(42), x => x * 2, () => 0) // 84\n * match(none, x => x * 2, () => 0) // 0\n */\nexport function match<T, U>(opt: Option<T>, onSome: (value: T) => U, onNone: () => U): U {\n return isSome(opt) ? onSome(opt) : onNone();\n}\n\n/**\n * Converts an Option to a Result, using a provided error if None.\n * @param opt - The Option to convert\n * @param error - Error value if None\n * @returns Ok(value) if Some, Err(error) if None\n * @example\n * okOr(some(42), 'missing') // Ok(42)\n * okOr(none, 'missing') // Err('missing')\n */\nexport function okOr<T, E>(opt: Option<T>, error: E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(error);\n}\n\n/**\n * Converts an Option to a Result, computing the error if None.\n * @param opt - The Option to convert\n * @param fn - Function to compute error\n * @returns Ok(value) if Some, Err(fn()) if None\n * @example\n * okOrElse(some(42), () => 'missing') // Ok(42)\n * okOrElse(none, () => 'missing') // Err('missing')\n */\nexport function okOrElse<T, E>(opt: Option<T>, fn: () => E): Result<T, E> {\n return isSome(opt) ? (opt as unknown as Ok<T>) : err(fn());\n}\n\n/**\n * Extracts the Ok value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(value) if Ok, None if Err\n * @example\n * ofOk(ok(42)) // Some(42)\n * ofOk(err('failed')) // None\n */\nexport function ofOk<T, E>(result: Result<T, E>): Option<T> {\n if (!isOk(result) || !isSome(result)) {\n return NONE;\n }\n return result as Some<T>;\n}\n\n/**\n * Extracts the Err value from a Result as an Option.\n * @param result - The Result to convert\n * @returns Some(error) if Err, None if Ok\n * @example\n * ofErr(err('failed')) // Some('failed')\n * ofErr(ok(42)) // None\n */\nexport function ofErr<T, E>(result: Result<T, E>): Option<E> {\n if (!isErr(result)) {\n return NONE;\n }\n const error = (result as { error: E }).error;\n if (!isSome(error)) {\n return NONE;\n }\n return error as Some<E>;\n}\n"],"names":["NONE","EMPTY","isSome","isNone","optionOf","of","err","isOk","isErr","NONE_PAIR","Object","freeze","fromNullable","value","fromPromise","promise","onRejected","error","unwrapOrReturn","opt","onNone","assertSome","message","Error","satisfiesOption","_","filterMap","values","fn","collected","mapped","push","findMap","map","result","undefined","flatMap","andThen","tap","tapNone","isNoneOr","predicate","filter","unwrap","unwrapOr","defaultValue","unwrapOrElse","expect","or","optb","orElse","xor","a","b","and","zip","other","unzip","mapOr","mapOrElse","defaultFn","flatten","contains","isSomeAnd","toArray","toNullable","toUndefined","match","onSome","okOr","okOrElse","ofOk","ofErr"],"mappings":"AAAA,SAASA,IAAI,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,YAAYC,EAAE,EAAEC,GAAG,EAAEC,IAAI,EAAEC,KAAK,QAAQ,aAAa;AAI3F,SAASN,MAAM,EAAEC,MAAM,EAAEE,EAAE,GAAG;AAE9B,MAAMI,YAAmCC,OAAOC,MAAM,CAAC;IAACX;IAAMA;CAAK;AAanE,OAAO,SAASY,aAAgBC,KAAwB;IACtD,OAAOR,GAAGQ;AACZ;AAWA,OAAO,eAAeC,YAAeC,OAAmC,EAAEC,UAAkD;IAC1H,IAAI;QACF,MAAMH,QAAQ,MAAME;QACpB,OAAOV,GAAGQ;IACZ,EAAE,OAAOI,OAAO;QACd,IAAI,CAACD,YAAY;YACf,OAAOhB;Q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