cont-flow-expr.try
TypeScript icon, indicating that this package has built-in type declarations

1.7.1 • Public • Published

cont-flow-expr.try

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;
});

API

try-catch

A basic try-catch expression can be written as:

import yrt from "cont-flow-expr.try";

const value = yrt(() => optionA).catch((error) => optionB);

TypeScript

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);

Benchmarks

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)

Related

License

The source code is licensed under the ISC license. The documentation text is licensed under CC BY 4.0.

Package Sidebar

Install

npm i cont-flow-expr.try

Weekly Downloads

3

Version

1.7.1

License

ISC

Unpacked Size

9.09 kB

Total Files

7

Last publish

Collaborators

  • ericcornelissen