1

I want to write a assert() function in Js. Something like this:

assert = function(condition, message) {
    if(condition) {
        console.log(message);
    } else {
        return return;
    }
}

But it's not true. We can write it like this:

assert = function(condition, message) {
    if(condition) {
        console.log(message);
        return true
    } else {
        return false;
    }
}

And use that like this:

function () {
     if(!assert(condition)) { return; }
     //Other Lines
}

But it could be better if we were be able to use that like this:

assert(condition, 'OK');

Is it possible to return a return? In fact have we any way to use something like to previous line to end a function by a assert?

Update:

My goal is end a function by a simple assert(condition) use, and not with use second conditions like if(!assert(condition)) { return; }.


p.s: I'm a newbie.

ali
  • 85
  • 1
  • 1
  • 9

2 Answers2

4

How about throwing an exception from assert if not true and otherwise nothing. That way, you can use them as you might be familiar already from other languages.

Code example:

assert = function(condition, message) {
    if(condition) {
        console.log(message);
    } else {
        throw "Assertion failed!";
    }
}
Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66
  • In that case can't you just use return assert(condition); – Roope Hakulinen Dec 17 '14 at 10:19
  • Hi @ali.: If this or any other answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Roope Hakulinen Dec 23 '14 at 13:24
2

It seems to me you just want to write less code. If you want to write lots of asserts then consider having a function that processes your list for you, then you only need to maintain an array of parameters:

var list = [
    [condition, 'OK'],
    [condition2, 'OK'],
    [condition3, 'OK'],
    [condition4, 'OK']
];

function runAsserts(asserts){
    for(var i = 0; i < asserts.length; i++){
        if(!assert(asserts[i][0], asserts[i][1])) { 
            return; 
        }
    }
}

Then you just call it with:

runAsserts(list);
musefan
  • 47,875
  • 21
  • 135
  • 185