What if you could write something like:
const value = try {
// Potentially failing commands
optionA;
} catch (error) {
// Recovering commands
optionB;
};
Enter, cont-flow-expr.try
:
import yrt from "cont-flow-expr.try";
const value = yrt(() => {
// Potentially failing commands
return optionA;
}).catch((error) => {
// Recovering commands
return optionB;
});
A basic try-catch
expression can be written as:
import yrt from "cont-flow-expr.try";
const value = yrt(() => optionA).catch((error) => optionB);
TypeScript support is included and can be used to ensure all branches evaluate to the same type (union). Type parameters are required for union types to work. For example:
import yrt from "cont-flow-expr.try";
const optionA = "foo", optionB = "bar", optionC = 42;
// Works
const aString = yrt(() => optionA)
.catch(() => optionB);
// Fails
const fails = yrt(() => optionA)
.catch(() => optionC);
// ~~~~~~~> TypeError:
// Type 'number' is not assignable to type 'string'.
// Works
const aStringOrNumber = yrt<string | number>(() => optionA)
.catch(() => optionC);
The benchmarks in this project - which are powered by Benchmark.js - can be used to compare this library against vanilla JavaScript as well as alternative libraries. Here's a sample result:
vanilla x 1,401,337,499 ops/sec ±0.15% (91 runs sampled)
cont-flow-expr x 70,774,351 ops/sec ±0.20% (96 runs sampled)
-
cont-flow-expr.if
- If statements as expressions. -
cont-flow-expr.switch
- Switch statements as expressions. -
cont-flow-expr
- Combines this and all of the above into one convenient package.
The source code is licensed under the ISC license. The documentation text is licensed under CC BY 4.0.