Skip to content

Propose Result.try to avoid syntax changes #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions polyfill.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,38 @@ interface ResultConstructor {
/**
* Creates a result for a successful operation
*/
ok<V>(value: V): Result<V>
ok<V>(this: void, value: V): Result<V>

/**
* Creates a result for a failed operation
*/
error<V>(error: unknown): Result<V>
error<V>(this: void, error: unknown): Result<V>

/**
* Runs a function and wraps the result into a {@linkcode Result}.
*
* @example
*
* const [ok, error, value] = Result.try(func, arg1, arg2)
* const [ok, error, value] = await Result.try(asyncFunc, arg1, arg2)
* const [ok, error, value] = await Result.try(async (arg) => arg, 'pass')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Javascript typically uses arg1, arg2, ... to notate variables that pass through, so examples 1 and 2 already seem to obviously pass through. This third example confuses the issue. It looks like a instruction, but I think you're just saying it's a variable that passes through.

*/
try<F extends (this: void, ...args: A[]) => R, A extends unknown[], R>(
this: void,
fn: F
): R extends Promise<infer P> ? Promise<Result<P>> : Result<R>

/**
* Wraps a promise into a {@linkcode Result}.
*
* The resulting promise never rejects.
*
* @example
*
* const [ok, error, value] = await Result.try(Promise.resolve('pass'))
* const [ok, error, value] = await Result.try(new Promise((rej) => rej('hello')))
*/
try<P extends Promise<R>, R>(this: void, promise: P): Promise<Result<R>>
}

declare const Result: ResultConstructor
18 changes: 18 additions & 0 deletions polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,22 @@ class Result {
static error(error) {
return new Result(false, error, undefined)
}

static try(fnOrPromise, ...args) {
if (fnOrPromise instanceof Promise) {
return fnOrPromise.then(Result.ok, Result.error)
}

try {
const result = fnOrPromise.apply(undefined, args)

if (result instanceof Promise) {
return result.then(Result.ok, Result.error)
}

return Result.ok(result)
} catch (error) {
return Result.error(error)
}
}
}