Skip to content

zagmi/tiny_invariant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

A tiny implementation of the invariant function in Dart

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages