@carbonteq/fp 0.7.0 → 0.8.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/result.js CHANGED
@@ -1,8 +1,8 @@
1
- import {
2
- __name
3
- } from "./chunk-7QVYU63E.js";
4
- import { isPromise } from "node:util/types";
5
- import { UNIT } from "./unit.js";
1
+ import { __name } from './chunk-7QVYU63E.js';
2
+ import assert from 'node:assert';
3
+ import { isPromise } from 'node:util/types';
4
+ import { UNIT } from './unit.js';
5
+
6
6
  class UnwrappedErrWithOk extends Error {
7
7
  static {
8
8
  __name(this, "UnwrappedErrWithOk");
@@ -19,246 +19,395 @@ class UnwrappedOkWithErr extends Error {
19
19
  super(`Attempted to call unwrap on an Err value: <${r}>`);
20
20
  }
21
21
  }
22
- const okPred = /* @__PURE__ */ __name((el) => el.isOk(), "okPred");
23
- const errPred = /* @__PURE__ */ __name((el) => el.isErr(), "errPred");
24
- const preds = [
25
- okPred,
26
- errPred
27
- ];
28
22
  const Sentinel = Symbol.for("ResultSentinel");
29
23
  class Result {
30
24
  static {
31
25
  __name(this, "Result");
32
26
  }
33
- val;
34
- error;
35
- static UNIT_RESULT = new Result(UNIT, null);
36
- constructor(val, error) {
37
- this.val = val;
38
- this.error = error;
27
+ static UNIT_RESULT = new Result(UNIT, {
28
+ errSlot: Sentinel
29
+ });
30
+ // Actual value holder. In async ops, will be used to chain. Cannot go back to normal after promise chain starts, although that could be looked into
31
+ #val;
32
+ // to prevent unnecessary chaining - no other purpose. Should be modifiable only within the creating method
33
+ #ctx;
34
+ constructor(val, ctx) {
35
+ this.#val = val;
36
+ this.#ctx = ctx;
39
37
  }
40
38
  static Ok(val) {
41
- return new Result(val, Sentinel);
39
+ return new Result(val, {
40
+ errSlot: Sentinel
41
+ });
42
42
  }
43
43
  static Err(err) {
44
- return new Result(Sentinel, err);
44
+ return new Result(Sentinel, {
45
+ errSlot: err
46
+ });
45
47
  }
46
48
  isOk() {
47
- return this.val !== Sentinel;
49
+ return this.#ctx.errSlot === Sentinel;
48
50
  }
49
51
  isErr() {
50
- return this.error !== Sentinel;
52
+ return this.#ctx.errSlot !== Sentinel;
51
53
  }
52
54
  isUnit() {
53
- return this.val === UNIT;
55
+ return this.#val === UNIT;
54
56
  }
55
57
  toString() {
56
- if (this.val !== Sentinel) {
57
- return `Result::Ok<${this.val}>`;
58
+ if (this.isOk()) {
59
+ return `Result::Ok<${String(this.#val)}>`;
58
60
  }
59
- return `Result::Err<${this.error}>`;
61
+ return `Result::Err<${String(this.#ctx.errSlot)}>`;
60
62
  }
61
63
  unwrap() {
62
- if (this.val === Sentinel) {
63
- if (this.error instanceof Error) throw this.error;
64
+ const curr = this.#val;
65
+ if (this.isErr()) {
66
+ const err = this.#ctx.errSlot;
67
+ if (err instanceof Error) throw err;
64
68
  throw new UnwrappedOkWithErr(this);
65
69
  }
66
- return this.val;
67
- }
68
- unwrapOr(def) {
69
- if (this.val === Sentinel) return def;
70
- return this.val;
71
- }
72
- unwrapOrElse(def) {
73
- if (this.val === Sentinel) return def();
74
- return this.val;
75
- }
76
- safeUnwrap() {
77
- return this.val === Sentinel ? null : this.val;
70
+ if (isPromise(curr)) {
71
+ return new Promise((resolve, reject) => {
72
+ curr.then((v) => {
73
+ if (v === Sentinel) {
74
+ let e;
75
+ if (this.#ctx.errSlot instanceof Error) e = this.#ctx.errSlot;
76
+ else e = new UnwrappedOkWithErr(this);
77
+ reject(e);
78
+ }
79
+ resolve(v);
80
+ }, reject);
81
+ });
82
+ }
83
+ return curr;
78
84
  }
79
85
  unwrapErr() {
80
- if (this.isOk()) {
81
- throw new UnwrappedErrWithOk(this);
86
+ const errSlot = this.#ctx.errSlot;
87
+ if (errSlot !== Sentinel) {
88
+ return errSlot;
89
+ }
90
+ const curr = this.#val;
91
+ if (isPromise(curr)) {
92
+ return new Promise((resolve, reject) => {
93
+ curr.then((v) => {
94
+ if (v !== Sentinel) {
95
+ reject(new UnwrappedErrWithOk(this));
96
+ }
97
+ resolve(this.#ctx.errSlot);
98
+ }, reject);
99
+ });
82
100
  }
83
- return this.error;
101
+ assert(curr !== Sentinel, "value must not be Sentinel at this point");
102
+ throw new UnwrappedErrWithOk(this);
84
103
  }
85
- safeUnwrapErr() {
86
- return this.error === Sentinel ? null : this.error;
104
+ safeUnwrap() {
105
+ return this.#val === Sentinel ? null : this.#val;
87
106
  }
88
107
  map(fn) {
89
- if (this.val === Sentinel) return Result.Err(this.error);
90
- const r = fn(this.val);
91
- if (isPromise(r)) {
92
- return r.then((val) => Result.Ok(val));
108
+ if (this.isErr()) return Result.Err(this.#ctx.errSlot);
109
+ assert(this.#val !== Sentinel, "cannot be Sentinel at this point");
110
+ const curr = this.#val;
111
+ const immutableCtx = this.#ctx;
112
+ const mutableCtx = {
113
+ errSlot: Sentinel
114
+ };
115
+ if (isPromise(curr)) {
116
+ const p = curr;
117
+ const out = p.then((v) => {
118
+ if (v === Sentinel) {
119
+ mutableCtx.errSlot = immutableCtx.errSlot;
120
+ return Sentinel;
121
+ }
122
+ const mapped = fn(v);
123
+ return mapped;
124
+ });
125
+ return new Result(out, mutableCtx);
93
126
  }
94
- return Result.Ok(r);
127
+ const next = fn(curr);
128
+ return new Result(next, mutableCtx);
95
129
  }
96
130
  /** Same as map, but for the error value instead of the Ok value */
97
131
  mapErr(fn) {
98
- if (this.error !== Sentinel) {
99
- const mappedErr = fn(this.error);
132
+ if (this.isErr()) {
133
+ const mappedErr = fn(this.#ctx.errSlot);
100
134
  return Result.Err(mappedErr);
101
135
  }
102
- return Result.Ok(this.val);
103
- }
104
- mapOr(default_, fn) {
105
- if (this.val === Sentinel) return default_;
106
- return fn(this.val);
107
- }
108
- mapOrAsync(default_, fn) {
109
- if (this.val === Sentinel) return Promise.resolve(default_);
110
- return fn(this.val);
136
+ const curr = this.#val;
137
+ const newCtx = {
138
+ errSlot: Sentinel
139
+ };
140
+ const ctx = this.#ctx;
141
+ if (isPromise(curr)) {
142
+ const p = curr.then((v) => {
143
+ if (ctx.errSlot !== Sentinel) {
144
+ const mappedErr = fn(ctx.errSlot);
145
+ newCtx.errSlot = mappedErr;
146
+ }
147
+ return v;
148
+ });
149
+ return new Result(p, newCtx);
150
+ }
151
+ return new Result(this.#val, newCtx);
111
152
  }
112
- /** For combining two results. For the lazy eval version, see {@link flatZip} and {@link zipAsync} */
113
- and(r) {
114
- if (this.isErr()) return this;
115
- if (r.isErr()) return r;
116
- return Result.Ok([
117
- this.val,
118
- r.val
119
- ]);
153
+ mapBoth(fnOk, fnErr) {
154
+ if (this.isErr()) {
155
+ return this.mapErr(fnErr);
156
+ }
157
+ if (isPromise(this.#val)) {
158
+ return this.map(fnOk);
159
+ }
160
+ return this.map(fnOk);
120
161
  }
121
162
  flatMap(fn) {
122
- if (this.val !== Sentinel) return fn(this.val);
123
- return Result.Err(this.error);
124
- }
125
- bind(fn) {
126
- if (this.val !== Sentinel) return fn(this.val);
127
- return Result.Err(this.error);
163
+ if (this.isErr()) return Result.Err(this.#ctx.errSlot);
164
+ assert(this.#val !== Sentinel, "cannot be Sentinel at this point");
165
+ const curr = this.#val;
166
+ const immutableCtx = this.#ctx;
167
+ const mutableCtx = {
168
+ errSlot: Sentinel
169
+ };
170
+ if (isPromise(curr)) {
171
+ const newP = new Promise((resolve, reject) => {
172
+ curr.then((v) => {
173
+ if (v === Sentinel) {
174
+ mutableCtx.errSlot = immutableCtx.errSlot;
175
+ return resolve(Sentinel);
176
+ }
177
+ const mapped2 = fn(v);
178
+ const p2 = Result.flatMapHelper(mutableCtx, mapped2);
179
+ resolve(p2);
180
+ }, reject);
181
+ });
182
+ return new Result(newP, mutableCtx);
183
+ }
184
+ const mapped = fn(curr);
185
+ const p = Result.flatMapHelper(mutableCtx, mapped);
186
+ return new Result(p, mutableCtx);
128
187
  }
129
- zipErr(fn) {
130
- if (this.val === Sentinel) return Result.Err(this.error);
131
- const r = fn(this.val);
132
- if (isPromise(r)) {
133
- return r.then((result) => result.map((_) => this.val));
188
+ static flatMapHelper(mutableCtx, mapped) {
189
+ if (isPromise(mapped)) {
190
+ return mapped.then((r) => Result.flatMapInnerHelper(mutableCtx, r));
191
+ }
192
+ return Result.flatMapInnerHelper(mutableCtx, mapped);
193
+ }
194
+ static flatMapInnerHelper(mutableCtx, r) {
195
+ if (isPromise(r.#val)) {
196
+ return r.#val.then((v) => {
197
+ if (v === Sentinel) {
198
+ mutableCtx.errSlot = r.#ctx.errSlot;
199
+ }
200
+ return v;
201
+ });
134
202
  }
135
- return r.map((_) => this.val);
203
+ if (r.#val === Sentinel) {
204
+ mutableCtx.errSlot = r.#ctx.errSlot;
205
+ return Sentinel;
206
+ }
207
+ return r.#val;
136
208
  }
137
- /** For running infallible side-effects on the contained value. Up to the programmer to ensure the underlying function doesn't fail */
138
- tap(fn) {
139
- if (this.val !== Sentinel) {
140
- fn(this.val);
209
+ zipErr(fn) {
210
+ if (this.isErr()) {
211
+ return Result.Err(this.#ctx.errSlot);
141
212
  }
142
- return this;
143
- }
144
- /**
145
- * Async version of {@link tap}
146
- * @see {@link tap}
147
- */
148
- async tapAsync(fn) {
149
- if (this.val !== Sentinel) {
150
- await fn(this.val);
213
+ assert(this.#val !== Sentinel, "cannot be Sentinel at this point");
214
+ const curr = this.#val;
215
+ const immutableCtx = this.#ctx;
216
+ const mutableCtx = {
217
+ errSlot: Sentinel
218
+ };
219
+ if (isPromise(curr)) {
220
+ const newP2 = curr.then((v) => {
221
+ if (v === Sentinel) {
222
+ mutableCtx.errSlot = immutableCtx.errSlot;
223
+ return Sentinel;
224
+ }
225
+ const r2 = fn(v);
226
+ return Result.zipErrHelper(v, r2, mutableCtx);
227
+ });
228
+ return new Result(newP2, mutableCtx);
151
229
  }
152
- return this;
230
+ const r = fn(curr);
231
+ const newP = Result.zipErrHelper(curr, r, mutableCtx);
232
+ return new Result(newP, mutableCtx);
153
233
  }
154
- zip(fn) {
155
- if (this.val === Sentinel) return Result.Err(this.error);
156
- const r = fn(this.val);
234
+ static zipErrHelper(v, r, newCtx) {
157
235
  if (isPromise(r)) {
158
- return r.then((u) => Result.Ok([
159
- this.val,
160
- u
161
- ]));
236
+ const finalPromise = r.then((newResult) => {
237
+ if (newResult.#ctx.errSlot !== Sentinel) newCtx.errSlot = newResult.#ctx.errSlot;
238
+ return v;
239
+ });
240
+ return finalPromise;
162
241
  }
163
- return Result.Ok([
164
- this.val,
165
- r
166
- ]);
242
+ if (r.#ctx.errSlot !== Sentinel) newCtx.errSlot = r.#ctx.errSlot;
243
+ return v;
167
244
  }
168
- flatZip(fn) {
169
- if (this.val === Sentinel) return Result.Err(this.error);
170
- const r = fn(this.val);
171
- if (isPromise(r)) {
172
- return r.then((other) => other.map((u) => [
173
- this.val,
174
- u
175
- ]));
245
+ zip(fn) {
246
+ if (this.isErr()) return Result.Err(this.#ctx.errSlot);
247
+ const curr = this.#val;
248
+ assert(this.#val !== Sentinel, "cannot be Sentinel at this point");
249
+ const immutableCtx = this.#ctx;
250
+ const mutableCtx = {
251
+ errSlot: Sentinel
252
+ };
253
+ if (isPromise(curr)) {
254
+ const newP = curr.then((v) => {
255
+ if (v === Sentinel) {
256
+ mutableCtx.errSlot = immutableCtx.errSlot;
257
+ return Sentinel;
258
+ }
259
+ const u2 = fn(v);
260
+ if (isPromise(u2)) return u2.then((uu) => [
261
+ v,
262
+ uu
263
+ ]);
264
+ return [
265
+ v,
266
+ u2
267
+ ];
268
+ });
269
+ return new Result(newP, mutableCtx);
176
270
  }
177
- return r.map((u) => [
178
- this.val,
271
+ const u = fn(curr);
272
+ if (isPromise(u)) {
273
+ return new Result(u.then((uu) => [
274
+ curr,
275
+ uu
276
+ ]), mutableCtx);
277
+ }
278
+ return new Result([
279
+ curr,
179
280
  u
180
- ]);
281
+ ], mutableCtx);
181
282
  }
182
- static all(c, seq) {
183
- const pred = preds[Number(c === "ok")];
184
- for (const el of seq) {
185
- if (!pred(el)) return false;
283
+ flatZip(fn) {
284
+ if (this.isErr()) return Result.Err(this.#ctx.errSlot);
285
+ const curr = this.#val;
286
+ assert(this.#val !== Sentinel, "cannot be Sentinel at this point");
287
+ const immutableCtx = this.#ctx;
288
+ const mutableCtx = {
289
+ errSlot: Sentinel
290
+ };
291
+ if (isPromise(curr)) {
292
+ const newP = curr.then((v) => {
293
+ if (v === Sentinel) {
294
+ mutableCtx.errSlot = immutableCtx.errSlot;
295
+ return v;
296
+ }
297
+ const mapped2 = fn(v);
298
+ return Result.flatZipHelper(mutableCtx, v, mapped2);
299
+ });
300
+ return new Result(newP, mutableCtx);
186
301
  }
187
- return true;
302
+ const mapped = fn(curr);
303
+ const p = Result.flatZipHelper(mutableCtx, curr, mapped);
304
+ return new Result(p, mutableCtx);
188
305
  }
189
- /** Whether any of the underlying results are Ok or Err */
190
- static any(c, seq) {
191
- const pred = preds[Number(c === "ok")];
192
- for (const el of seq) {
193
- if (pred(el)) return true;
306
+ static flatZipHelper(mutableCtx, originalVal, mapped) {
307
+ if (isPromise(mapped)) {
308
+ return mapped.then((r) => Result.flatZipInnerHelper(mutableCtx, originalVal, r));
194
309
  }
195
- return false;
196
- }
197
- /**
198
- * `Result.sequence(Result<T1, E1>, Result<T2, E2>, ...)` will return `Result<[T1, T2, ...], E1 | E2 | ...>`
199
- * @example
200
- * const r1 = Result.Ok<string, string>("abc")
201
- * const r2 = Result.Ok<number, Error>(123)
202
- * const r = Result.sequence(r1, r2) // r will be of type Result<[string, number], string | Error>
203
- */
204
- static sequence(...results) {
205
- const vals = [];
206
- for (const r of results) {
207
- if (r.isErr()) return r;
208
- vals.push(r.unwrap());
310
+ return Result.flatZipInnerHelper(mutableCtx, originalVal, mapped);
311
+ }
312
+ static flatZipInnerHelper(mutableCtx, originalVal, r) {
313
+ if (isPromise(r.#val)) {
314
+ return r.#val.then((v) => {
315
+ if (v === Sentinel) {
316
+ mutableCtx.errSlot = r.#ctx.errSlot;
317
+ }
318
+ return [
319
+ originalVal,
320
+ v
321
+ ];
322
+ });
209
323
  }
210
- return Result.Ok(vals);
211
- }
212
- /** Convert a Result of a Promise to the Promise of a Result */
213
- static async lift(r) {
214
- if (r.isErr()) return Promise.resolve(Result.Err(r.error));
215
- return r.val.then((v) => Result.Ok(v));
324
+ if (r.#val === Sentinel) {
325
+ mutableCtx.errSlot = r.#ctx.errSlot;
326
+ return Sentinel;
327
+ }
328
+ return [
329
+ originalVal,
330
+ r.#val
331
+ ];
216
332
  }
217
333
  //#endregion
218
- // static innerMap<T, U, E>(
219
- // r: Result<Array<T>, E>,
220
- // mapper: (val: T) => U,
221
- // ): Result<Array<U>, E> {
222
- // return r.map((inner) => inner.map(mapper));
223
- // }
224
- // innerMap<Inner, U>(
225
- // this: Result<Array<Inner>, E>,
226
- // mapper: (val: T) => U,
227
- // ): Result<Array<U>, E>;
228
- // innerMap<U>(this: Result<unknown, E>, mapper: (val: T) => U): never;
229
- // innerMap<U>(this: Result<unknown, E>, mapper: (val: T) => U) {
230
- // if (this.val === Sentinel) return this;
231
- //
232
- // if (Array.isArray(this.val)) {
233
- // return Result.Ok(this.val.map(mapper));
234
- // }
235
- //
236
- // throw new Error("Can only be called for Result<Array<T>, E>");
237
- // }
238
334
  innerMap(mapper) {
239
- if (this.val === Sentinel) return this;
240
- if (Array.isArray(this.val)) {
241
- return Result.Ok(this.val.map(mapper));
335
+ if (this.isErr()) return this;
336
+ if (Array.isArray(this.#val)) {
337
+ return new Result(this.#val.map(mapper), this.#ctx);
242
338
  }
243
339
  throw new Error("Can only be called for Result<Array<T>, E>");
244
340
  }
245
- pipe(...fns) {
246
- let res3 = this;
247
- for (const fn of fns) {
248
- res3 = res3.map(fn);
341
+ async toPromise() {
342
+ const v = await this.#val;
343
+ return new Result(v, this.#ctx);
344
+ }
345
+ validate(validators) {
346
+ if (this.isErr()) return this;
347
+ const currVal = this.#val;
348
+ const currCtx = this.#ctx;
349
+ const mutableCtx = {
350
+ errSlot: Sentinel
351
+ };
352
+ if (isPromise(currVal)) {
353
+ return new Result(currVal.then(async (c) => {
354
+ if (currCtx.errSlot !== Sentinel) {
355
+ mutableCtx.errSlot = currCtx.errSlot;
356
+ return Sentinel;
357
+ }
358
+ const results2 = validators.map((v) => v(currVal));
359
+ return Promise.all(results2).then((resolved) => Result.validateHelper(resolved, mutableCtx, c));
360
+ }), mutableCtx);
361
+ }
362
+ const results = validators.map((v) => v(currVal));
363
+ if (results.some(isPromise)) {
364
+ return new Result(Promise.all(results).then((resolved) => Result.validateHelper(resolved, mutableCtx, currVal)), mutableCtx);
365
+ }
366
+ const values = results.map((r) => r.#val);
367
+ if (values.some(isPromise)) {
368
+ return new Result(Result.validateHelper(results, mutableCtx, currVal), mutableCtx);
249
369
  }
250
- return res3;
370
+ const combinedRes = Result.all(...results);
371
+ return combinedRes.isErr() ? combinedRes : this;
372
+ }
373
+ static validateHelper(results, currCtx, currVal) {
374
+ const combinedRes = Result.all(...results);
375
+ if (isPromise(combinedRes)) {
376
+ return combinedRes.then((cRes) => {
377
+ if (cRes.isErr()) {
378
+ currCtx.errSlot = cRes.#ctx.errSlot;
379
+ return Sentinel;
380
+ }
381
+ return currVal;
382
+ });
383
+ }
384
+ if (combinedRes.isErr()) {
385
+ currCtx.errSlot = combinedRes.#ctx.errSlot;
386
+ return Sentinel;
387
+ }
388
+ return currVal;
389
+ }
390
+ static all(...results) {
391
+ const vals = results.map((r) => r.#val);
392
+ const mutableCtx = {
393
+ errSlot: Sentinel
394
+ };
395
+ if (vals.some(isPromise)) {
396
+ return new Result(Promise.all(vals).then((v) => {
397
+ if (results.some((r) => r.isErr())) {
398
+ mutableCtx.errSlot = results.filter((r) => r.isErr()).map((r) => r.#ctx.errSlot);
399
+ return Sentinel;
400
+ }
401
+ return v;
402
+ }), mutableCtx);
403
+ }
404
+ if (results.some((r) => r.isErr())) {
405
+ return Result.Err(results.filter((r) => r.isErr()).map((r) => r.#ctx.errSlot));
406
+ }
407
+ return Result.Ok(vals);
251
408
  }
252
409
  }
253
- const res = Result.Ok([
254
- 1,
255
- 2,
256
- 3
257
- ]);
258
- const res2 = Result.Ok(123);
259
- export {
260
- Result,
261
- UnwrappedErrWithOk,
262
- UnwrappedOkWithErr
263
- };
410
+
411
+ export { Result, UnwrappedErrWithOk, UnwrappedOkWithErr };
412
+ //# sourceMappingURL=result.js.map
264
413
  //# sourceMappingURL=result.js.map