2

I'm trying to build a pivot-table javascript application with jQuery, and I want to let the user defines its own calculated fields (just as seen on Excel!).

So, if f1, f2, f3 are the columns of the table, users can define a custom field as c1 = (f1 + f2)/f3 just by typing (as I can do with Excel).

I guess I need a parser, to make sure that:

  • f1, f2, f3 are valid table fields (while f4 is not)
  • there are no invalid symbols.

Any suggestion (ready-to-use plugins, examples,...?)?

Thank you

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
franz976
  • 333
  • 3
  • 14
  • Just use Javascript objects to design your table's columns as they're first typed. Then you can just query your object for columns, and if the value is undefined then the column doesn't exist. – Platinum Azure Jan 31 '11 at 22:08

2 Answers2

0

you can use javascript's eval() function to a degree. You only have to replace variables with their values which is pretty easy.

eval("f1 + f2 / f3".replace("f1","6").replace("f2","8").replace("f3","4"));

Outputs:

  8
Aliostad
  • 80,612
  • 21
  • 160
  • 208
0

Start with the code from here: http://jsfromhell.com/classes/math-processor

add something like:

    if(e.length >= 2 && e[0] == 'f') {
        i = "0123456789".indexOf(e[1]);
        if(i >= 0) {
            e.splice(0,2);
            return [_.get_var(i), , , 0];
        }
    }

after:

p.v = function(e){
    var i, j, l, _ = this;

Then you can set your variables and use them like this: (only supports f0 to f9):

var mp = new MathProcessor();
var myVars = {3:55}; // your vars -- f3 = 55
mp.get_var = function(x) {return myVars[x];}
alert(mp.parse('4+f3*2'));

See this example at: http://jsfiddle.net/amirshim/mcJe4/

Go to the bottom of the fiddle to play with it.

Amir
  • 4,131
  • 26
  • 36