node-arse.js

(function() {

Since this extends the assert module, we need to include it

    var assert = require('assert');
    

The work starts here

Our lovely little workhorse. Wraps around any function and catches all exceptions that the function throws. The error is then passed to a callback

    function callbackWrap(target) {
        return function() {
            var targetArguments, callback;
            var __slice = Array.prototype.slice;
            

Since we're adding a callback as the final argument we need to retrieve the first n-1 parameters which will get passed to the function

            targetArguments = __slice.call(arguments, 0, arguments.length - 1);

Now to fetch the callback which is called if there's an exception

            callback = arguments[arguments.length - 1];
            

Run the function and catch any exceptions. Returns true or false depending on whether the assertion held. This boolean can be used to control program flow.

            try {
                target.apply(this, targetArguments)
                return true
            } catch(error) {
                callback(error)
                return false
            }
        }
    }
    

Extra assertions

    

Tests if value is less than target

    function lessThan(value, target, message) {
        if (value >= target) {
            assert.fail(value, '< ' + target, message, 'lessThan');
        }
    }
    

Tests if value if less than or equal to target

    function lessThanEqual(value, target, message) {
        if (value > target) {
            assert.fail(value, '<= ' + target, message, 'lessThanEqual');
        }
    }
    

Tests if value is greater than target

    function greaterThan(value, target, message) {
        if (value <= target) {
            assert.fail(value, '> ' + target, message, 'greaterThan');
        }
    }
    

Tests if value is greater than or equal to target

    function greaterThanEqual(value, target, message) {
        if (value < target) {
            assert.fail(value, '>= ' + target, message, 'greaterThanEqual');
        }
    }
    

Helpers

Simple function to loop through a given object and wrap the functions to accept a callback as their final argument

    function extend(target, source) {
        Object.keys(source).forEach(function(property) {
            if (typeof source[property] === 'function') {
                target[property] = callbackWrap(source[property]);
            }
        });
    }
    

Extend the assert module so all its functions accept callbacks

    extend(exports, assert);
    
    exports.lessThan = callbackWrap(lessThan);
    exports.lessThanEqual = callbackWrap(lessThanEqual)
    exports.greaterThan = callbackWrap(greaterThan);
    exports.greaterThanEqual = callbackWrap(greaterThanEqual)
}).call(this);