1.7.1 • Published 1 year ago

cont-flow-expr.try v1.7.1

Weekly downloads
-
License
ISC
Repository
gitlab
Last release
1 year ago

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.

1.7.1

1 year ago

1.7.0

2 years ago

1.6.0

2 years ago

1.5.0

2 years ago

1.4.0

2 years ago