JSFiddle - React, Tailwind, and code Playground

by ernestohs

JavaScript

Case = function (predicate, action) {  
    this.predicate = predicate;
    this.action = action;
};


Case.prototype = {
    
    nomatch : { match : false },
    
    match : function (v) { return { match : true, result :v }; },

    evaluate : function( object ) {
        var match = this.predicate;

        if ( match instanceof Function )
            match = match( object );

        if ( match ) {

            if (this.action instanceof Function )
                return this.match( this.action(object) );

            if ( this.action instanceof Case )
                return this.action.evaluate( object );

            if ( this.action instanceof Array ) {
                var decision;
                var result;
                for (var c = 0; c < this.action.length; c++ ) {
                    decision = this.action[c];
                    if ( decision instanceof Case )  {
                        result = decision.evaluate( object );
                        if (result.match)
                            return result;
                    } else throw("Array of Case expected");
                }

                return this.nomatch;
            }

            return this.match(this.action);
        } 
        return this.nomatch;
    }
};


var desition = new Case(true, Array(

    new Case(function(x){ return x > 80;} , "Proceed to Desire (high score)"),
    new Case(function(x){ return (x >= 40) && (x <= 80);} , "More: three additional Awareness questions"),
    new Case(function(x){ return x < 40;} , "Terminate: this is barrier, maybe a few planning questions")
    
));

document.write(desition.evaluate(39).result+ '<BR/>' );
document.write(desition.evaluate(50).result+ '<BR/>'  );
document.write(desition.evaluate(81).result+ '<BR/>'  );