A tiny invariant
alternative in Dart.
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());
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?`);
condition
is required and can be anythingmessage
optionalstring
or a function that returns astring
dart pub add tiny_invariant
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);
}
}