Sunday, May 1, 2011

Chaining Assert for JavaScript

Sometimes it's really handy to be able to assert various states. Even though JavaScript does not provide a native statement for this purpose, it's really easy to implement one as this example shows.

I took the syntax a bit further and ended up with a chaining version. The current version provides following features:

  • Chaining syntax (d'oh). Example: assert(a).is('number').between(0, 10);
  • "equals" method. Example: assert(a).equals('supercow');
  • "between" method. Example: assert(a).between(10, 20);. This means "a" should be within given range, ends included.
  • Basic type checks borrowed from RightJS. Example: assert(a).is('number', 'array'); meaning "a" should be either a number or an array.
  • "isDefined" method. Example: assert(a).isDefined() meaning "a" should not be "undefined".
  • Special "not" method that inverts the result of the following method. Example: assert(a).not().is('number'); . I admit it does not read that well in this case. It's way better with something like "between" or "equals".
  • Extensible architecture. It should be quite easy to tweak it to fit your tastes.

Here's the code in its entirety for those interested (not visible in RSS!):