Search code examples
javascriptassert

Ensure that a condition is always true in JavaScript


In JavaScript, is it possible to test whether a condition remains true throughout a program's entire execution? Here, I want to ensure that the variable a is always divisible by 3, from the start of the program to the end.

//Assert that the following is always true, and print an error message if not true
ensureAlwaysTrue(a % 3 == 0); //print an error message if a is not divisible by 0
                              //from this point onward

a = 6;

a = 10 //print error message, since a % 3 != 0

function ensureAlwaysTrue(){
    //this is the function that I'm trying to implement.
}

One solution would be add statements to check the assertions after every single variable assignment, but that would be redundant and cumbersome. Is there a more concise way to check whether a condition is true throughout a program's execution?


Solution

  • Based on the idea from @Chris (http://stackoverflow.com/a/14534019/1394841), you could enclose your whole code in a string, and then do something like:

    function ensureAlwaysTrue(condition, code)
    {
        var statements = code.split(";");
        for (var i = 0; i < statements.length-1; i++) { //last statement is empty
            eval(statements[i] + ";");
            if (!condition()) error();
            //break; //if desired
        }
    }
    
    var code =
    "a = 6;\
    a = 10; //print error message, since a % 3 != 0\
    ";
    
    ensureAlwaysTrue(function(){return (a % 3 == 0);}, code);