functionalscript
Version:
FunctionalScript is a purely functional subset of JavaScript
47 lines (46 loc) • 1.21 kB
JavaScript
/**
* A module for representing and handling operations that can succeed or fail.
*
* @module
*
* @example
*
* ```ts
* import { error, ok, unwrap, type Result } from './module.f.ts'
*
* const success: Result<number, string> = ok(42)
* const failure: Result<number, string> = error('Something went wrong')
*
* if (unwrap(success) !== 42) { throw 'error' }
* const [kind, v] = failure
* if (kind !== 'error') { throw 'error' }
* // `v` is inferred as `string` here
* if (v !== 'Something went wrong') { throw 'error' }
* ```
*/
/**
* Creates a successful result.
*
* @param value - The value to wrap.
* @returns A successful result containing the value.
*/
export const ok = (value) => ['ok', value];
/**
* Creates a failed result.
*
* @param e - The error to wrap.
* @returns A failed result containing the error.
*/
export const error = (e) => ['error', e];
/**
* Unwraps a result, returning the value if successful or throwing the error if failed.
*
* @param param0 - The result to unwrap.
* @returns The value if the result is successful. Otherwise, throws the error.
*/
export const unwrap = ([kind, v]) => {
if (kind === 'error') {
throw v;
}
return v;
};