@lodestar/utils
Version:
Utilities required across multiple lodestar packages
80 lines • 2.25 kB
JavaScript
const symErr = Symbol("err");
export function Err(error) {
return { [symErr]: true, error };
}
/**
* Typeguard for Err<T>. Allows the pattern
* ```ts
* function getNumSquare(): Result<number, Error> {
* const value = getNum();
* if (isErr(value)) {
* return value; // return as error
* }
* return value ** 2;
* }
* function getNum(): Result<number, Error>
* ```
* Since the non-error is not wrapped, it uses a symbol to prevent collisions
*/
export function isErr(result) {
return result !== null && typeof result === "object" && result[symErr] === true;
}
/**
* Given an array of results, run a function only on an array of ok results.
* Returns a new array of results with same length as `results` where the ok
* value may be Err or T2.
*/
export function mapOkResults(results, fn) {
const oks = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (!isErr(result)) {
oks.push(result);
}
}
const outOksResults = fn(oks);
if (outOksResults.length !== oks.length) {
throw Error("mapOkResults fn must return same length");
}
const outResults = [];
for (let i = 0, j = 0; i < results.length; i++) {
const result = results[i];
if (isErr(result)) {
outResults.push(result);
}
else {
outResults.push(outOksResults[j]);
j++;
}
}
return outResults;
}
/**
* See {@link mapOkResults} but `fn` is async
*/
export async function mapOkResultsAsync(results, fn) {
const oks = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (!isErr(result)) {
oks.push(result);
}
}
const outOksResults = await fn(oks);
if (outOksResults.length !== oks.length) {
throw Error("mapOkResults fn must return same length");
}
const outResults = [];
for (let i = 0, j = 0; i < results.length; i++) {
const result = results[i];
if (isErr(result)) {
outResults.push(result);
}
else {
outResults.push(outOksResults[j]);
j++;
}
}
return outResults;
}
//# sourceMappingURL=err.js.map