Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a complicated decision table in JavaScript

Tags:

javascript

Here's an implementation details question for JavaScript gurus.

I have a UI with a number of fields in which the values of the fields depend in a complicated fashion on the values of seven bits of inputs. Exactly what should be displayed for any one of the possible 128 values that is changing regularly as users see more of the application?

Right now, I've for this being implemented as a decision tree through an if-then-else comb, but it's brittle under the requirements changes and sort of hard to get right.

One implementation approach I've thought about is to make an array of values from 0x0 to 0x7F and then store a closure at each location --

var tbl; // initialize it with the values
  ...
tbl[0x42] = function (){ doAThing(); doAnotherThing(); }

and then invoke them with

tbl[bitsIn]();

This, at least makes the decision logic into a bunch of assignments.

Question: is there a better way?

(Update: holy crap, how'd that line about 'ajax iphone tags' get in there? No wonder it was a little puzzling.)

Update

So what happened? Basically I took a fourth option, although similar to the one I've checked. The logic was sufficiently complex that I finally built a Python program to generate a truth table in the server (generating Groovy code, in fact, the host is a Grails application) and move the decision logic into the server completely. Now the JavaScript side simply interprets a JSON object that contains the values for the various fields.

Eventually, this will probably go through one more iteration, and become data in a database table, indexed by the vector of bits.

The table driven part certainly came out to be the way to go; there have already been a half dozen new changes in the specific requirements for display.

like image 942
Charlie Martin Avatar asked Jan 12 '11 21:01

Charlie Martin


1 Answers

I see two options...

Common to both solutions are the following named functions:

function aThing() {}
function anotherThing() {}
function aThirdThing() {}

The switch way

function exec(bits) {
 switch(bits) {
    case 0x00: aThing(); anotherThing(); break;
    case 0x01: aThing(); anotherThing(); aThirdThing(); break;
    case 0x02: aThing(); aThirdThing(); break;
    case 0x03: anotherThing(); aThirdThing(); break;
    ...
    case 0x42: aThirdThing(); break;
    ...
    case 0x7f: ... break;
    default: throw 'There is only 128 options :P';
  }
}

The map way

function exec(bits) { 
    var actions = map[bits];
    for(var i=0, action; action=actions[i]; i++)
        action(); 
}

var map = {
 0x00: [aThing, anotherThing],
 0x01: [aThing, anotherThing, aThirdThing],
 0x02: [aThing, aThirdThing],
 0x03: [anotherThing, aThirdThing],
    ...
 0x42: [aThirdThing],
    ...
};

in both cases you'd call

exec(0x42);
like image 132
Martin Jespersen Avatar answered Sep 28 '22 04:09

Martin Jespersen