Skip to content

Commit

Permalink
feat: adds unwrapOr
Browse files Browse the repository at this point in the history
  • Loading branch information
OctoD committed Jul 15, 2019
1 parent e0ca437 commit d3fd93b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,21 @@ class Result<R, E> {

return this.value;
}

/**
* Unwraps a result, yielding the content of an `Ok`. Else, it returns `optb`.
* @template U
* @param {U} optb
* @returns {(R | U)}
* @memberof Result
*/
public unwrapOr<U>(optb: U): R | U {
if (instanceOfError<R, E>(this.value)) {
return optb;
}

return this.value;
}
}

/**
Expand Down
5 changes: 5 additions & 0 deletions src/__tests__/Result.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,9 @@ describe(`Result`, () => {
expect(Ok("a").unwrap()).toBe("a");
expect(() => Err("a").unwrap()).toThrowError();
});

it("Unwraps a result, yielding the content of an `Ok`. Else, it returns `optb`.", () => {
expect(Ok("a").unwrapOr(Ok("b"))).toBe("a");
expect(Err("a").unwrapOr("b")).toBe("b");
});
});

0 comments on commit d3fd93b

Please sign in to comment.