Skip to content

Commit

Permalink
add async map
Browse files Browse the repository at this point in the history
  • Loading branch information
volf52 committed Jul 11, 2024
1 parent 66a5162 commit 7db4034
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/tall-coins-buy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@carbonteq/fp": patch
---

Add async map
15 changes: 10 additions & 5 deletions src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,18 @@ export class Result<T, E> {
* const result1 = r.map(mapper) // Result containing 64 as the ok value
* const result2 = r2.map(mapper) // mapper won't be applied, as r2 was in error state
*/
map<U>(f: Mapper<T, U>): Result<U, E> {
if (this.val === Sentinel)
return new Result(Sentinel, this.error) as Result<U, E>;
map<U>(fn: (val: T) => U): Result<U, E>;
map<U>(fn: (val: T) => Promise<U>): Promise<Result<U, E>>;
map<U>(fn: Mapper<T, U> | AsyncMapper<T, U>) {
if (this.val === Sentinel) return Result.Err(this.error);

const r = fn(this.val);

const valPrime = f(this.val);
if (isPromise(r)) {
return r.then((val) => Result.Ok(val) as Result<U, E>);
}

return new Result(valPrime, this.error);
return Result.Ok(r) as Result<U, E>;
}

/** Same as map, but for the error value instead of the Ok value */
Expand Down

0 comments on commit 7db4034

Please sign in to comment.