tiny_invariant 1.0.0+2 copy "tiny_invariant: ^1.0.0+2" to clipboard
tiny_invariant: ^1.0.0+2 copied to clipboard

A tiny implementation of the invariant function in Dart.

Tiny Invariant #


A tiny invariant alternative in Dart.

What is invariant? #

An invariant function takes a value, and if the value is falsy then the invariant function will throw. If the value is truthy, then the function will not throw.

import 'package:tiny_invariant/tiny_invariant.dart';

invariant(truthyValue, 'This should not throw!');

invariant(falsyValue, 'This will throw!');
// Error('Invariant violation: This will throw!');

You can also provide a function to generate your message, for when your message is expensive to create

import 'package:tiny_invariant/tiny_invariant.dart';

invariant(value, () => getExpensiveMessage());

Why tiny_invariant? #

The initial implementation from where I got the idea library: invariant supports passing in arguments to the invariant function in a sprintf style (condition, format, a, b, c, d, e, f). It has internal logic to execute the sprintf substitutions. The sprintf logic is not removed in production builds. tiny_invariant has dropped all of the sprintf logic. tiny_invariant allows you to pass a single string message.

invariant(condition, `Hello, ${name} - how are you today?`);

API: (condition: T, message: String?) #

  • condition is required and can be anything
  • message optional string or a function that returns a string

Installation #

dart pub add tiny_invariant

Dropping your message for kb savings! #

Big idea: you will want your compiler to convert this code:

invariant(condition, 'My cool message that takes up a lot of kbs');

Into this:

if (!condition) {
  if ('production' !== process.env.NODE_ENV) {
    invariant(false, 'My cool message that takes up a lot of kbs');
  } else {
    invariant(false);
  }
}
1
likes
135
pub points
0%
popularity

Publisher

unverified uploader

A tiny implementation of the invariant function in Dart.

Repository (GitHub)
View/report issues

Documentation

API reference

License

BSD-2-Clause (LICENSE)

More

Packages that depend on tiny_invariant