krash

0.1.3 • Public • Published

krash

fluent assert for validation of invariants before assignment.

NPM build status js-standard-style

motivation

bare-bones inline assertion of invariants when assigning a value to a variable (detailed example below)

var delicate = krash.unless(suspect, isDefined, 'suspect not defined')

particularly helpful together with your favorite library of predicates such as lodash/Lang, predicate, predicates, ...

note that it's easy to use a shorter alias for krash.unless, for example:

var assert = require('krash').unless
...
var delicate = assert(suspect, isDefined, 'suspect not defined')
...

krash also comes with a helper for throwing, that helps with formating the error message: krash.now(...message)

usage

example

var krash = require('krash')
 
function fun (suspect) {
  // assert the invariants:
  // assign suspect to delicate if defined, otherwise throw 'suspect not defined'
  var delicate = krash.unless(suspect, isDefined, 'suspect not defined')
}
 
// example of predicate that returns a boolean
function isDefined (val) {
  return (typeof val !== 'undefined') && (val !== null)
}
 
fun(undefined) // throw 'suspect not defined'

signatures

krash.unless(val: any, predicate: function, ...message: string[])

  • val any the value to check against the predicate and return if valid
  • predicate function given val, returns a boolean
  • ...message string[] the remaining arguments are assembled by util#format to generate the error message
  • return any val if predicate(val) is true
  • throw ...message if predicate(val) is false

krash.now(...message: string[])

  • ...message string[] the arguments are assembled by util#format to generate the error message
  • throw ...message

status

stable

license

(C) Copyright 2015, bzb-stcnx, MIT

Package Sidebar

Install

npm i krash

Weekly Downloads

318

Version

0.1.3

License

SEE LICENSE IN ./LICENSE

Last publish

Collaborators

  • bzb-stcnx