+
1
|
list
|
skin
|
login
|
editor
α-wwwiki
::
evaluator2
user:none
(2469 bytes)
_h3 8-evaluator (see [[evaluator3]]) _p Following the previous [[evaluator]], this is another way to integrate the code in the page : the code is written in a container and loaded in a script tag dynamically created. How to use it : _ul first "init the evaluator", only once, _ul copy a line from the examples in the code, _ul paste it into the field below, _ul then click on the button "evaluate" _ul and do it again with new values. {hr} First {input {@ type="submit" value="init evaluator" onclick="°° var js = document.createElement('script'); var input = getId('code').innerHTML; js.innerHTML = decode_html_entities(input); // < ,> document.head.appendChild( js ); this.value = 'OK, evaluator inited !'; this.disabled='disabled'; °°"}} then {input {@ type="submit" value="evaluate" onclick="do_evaluate()"}} {input {@ id="input" type="texte" value="['sqrt', ['+', ['*',3,3], ['*',4,4]]]" style="width:99%; font:normal 1em courier; color:red;background:#ffc;"}} {pre {@ id="output"}} _h3 evaluator's code {pre {@ id="code"}°° // 1) evaluator var evaluate = function(str) { var expression = eval( str ), rest = []; if (!Array.isArray(expression)) return expression.toString(); var first = expression.shift(); if (!dico.hasOwnProperty(first)) return 'Sorry, [' + first + '] is not in dico !'; expression.map(function(a){rest.push(evaluate(a))}) return dico[first](rest); }; // 2) functions dictionary var dico = { '+': function(a) { return a.reduce(function(x,y){return Number(x)+Number(y)}) }, '*': function(a) { return a.reduce(function(x,y){return x*y}) }, '-': function(a) { return (a.length == 1)? -a[0] : a.reduce(function(x,y){return x-y}) }, '/': function(a) { return (a.length == 1)? 1/a[0] : a.reduce(function(x,y){return x/y}) }, 'sqrt' : function(a) { return Math.sqrt( a ) }, 'pow' : function(a) { return Math.pow( a[0], a[1] ) }, 'square': function(a) { return a[0]*a[0] }, 'hypo' : function(a) { return Math.sqrt( a[0]*a[0] + a[1]*a[1] ) }, 'fac' : function(a) { return (a< 2)? 1 : a*arguments.callee(a-1); } // and so on. }; // 3) HTML interface function do_evaluate() { getId('output').innerHTML = evaluate( getId('input').value ); } °°} _h3 examples {pre ['+',1,2,3,4,5,6] ['*',1,2,3,4,5,6] ['+', ['*',3,3], ['*',4,4]] ['*', ['+',3,3], ['+',4,4]] ['sqrt', 2] ['pow',2,8] ['sqrt', ['+', ['*',3,3], ['*',4,4]]] ['hypo',3,4] ['fac',6] }