-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
8 changed files
with
547 additions
and
326 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License; | ||
* you may not use this file except in compliance with the Elastic License. | ||
*/ | ||
|
||
export interface Ok<T> { | ||
tag: 'ok'; | ||
value: T; | ||
} | ||
|
||
export interface Err<E> { | ||
tag: 'err'; | ||
error: E; | ||
} | ||
export type Result<T, E> = Ok<T> | Err<E>; | ||
|
||
export function asOk<T>(value: T): Ok<T> { | ||
return { | ||
tag: 'ok', | ||
value, | ||
}; | ||
} | ||
|
||
export function asErr<T>(error: T): Err<T> { | ||
return { | ||
tag: 'err', | ||
error, | ||
}; | ||
} | ||
|
||
export function isOk<T, E>(result: Result<T, E>): result is Ok<T> { | ||
return result.tag === 'ok'; | ||
} | ||
|
||
export function isErr<T, E>(result: Result<T, E>): result is Err<E> { | ||
return !isOk(result); | ||
} | ||
|
||
export async function promiseResult<T, E>(future: Promise<T>): Promise<Result<T, E>> { | ||
try { | ||
return asOk(await future); | ||
} catch (e) { | ||
return asErr(e); | ||
} | ||
} | ||
|
||
export function map<T, E, Resolution>( | ||
result: Result<T, E>, | ||
onOk: (value: T) => Resolution, | ||
onErr: (error: E) => Resolution | ||
): Resolution { | ||
return isOk(result) ? onOk(result.value) : onErr(result.error); | ||
} |
Oops, something went wrong.