Skip to content

Commit

Permalink
feat: try$
Browse files Browse the repository at this point in the history
  • Loading branch information
Benricheson101 committed Dec 28, 2024
1 parent 5952bed commit 3d8b4a0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
10 changes: 10 additions & 0 deletions lib/error/try.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,14 @@ describe('error/try$', () => {
deepStrictEqual(f(3), [null, 3]);
deepStrictEqual(f(4), [null, 4]);
});

it('should retain `this`', () => {
const f = try$(function (this: string) {
return this;
});

const g = f.bind('test');

deepStrictEqual(g(), ['test', null]);
});
});
6 changes: 2 additions & 4 deletions lib/error/try.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
export type ResultTuple<T, E = unknown> =
| readonly [T, null]
| readonly [null, E];
export type Result<T, E = unknown> = readonly [T, null] | readonly [null, E];

/** wraps a function to return `[T, E]` instead of `T throws E` */
export const try$ = <E, F extends (...args: Parameters<F>) => ReturnType<F>>(
Expand All @@ -9,7 +7,7 @@ export const try$ = <E, F extends (...args: Parameters<F>) => ReturnType<F>>(
function (
this: ThisParameterType<F>,
...args: Parameters<F>
): ResultTuple<ReturnType<F>, E> {
): Result<ReturnType<F>, E> {
try {
return [f.apply(this, args) as ReturnType<F>, null];
} catch (err) {
Expand Down

0 comments on commit 3d8b4a0

Please sign in to comment.