function_transform.js (1275B)
1 /** 2 * Function transforms 3 * 4 * When using functions via the expression parser, it is possible to preprocess 5 * function arguments and post process a functions return value by writing a 6 * *transform* for the function. A transform is a function wrapping around a 7 * function to be transformed or completely replaces a function. 8 */ 9 const { create, all } = require('../..') 10 const math = create(all) 11 12 // create a function 13 function addIt (a, b) { 14 return a + b 15 } 16 17 // attach a transform function to the function addIt 18 addIt.transform = function (a, b) { 19 console.log('input: a=' + a + ', b=' + b) 20 // we can manipulate the input arguments here before executing addIt 21 22 const res = addIt(a, b) 23 24 console.log('result: ' + res) 25 // we can manipulate the result here before returning 26 27 return res 28 } 29 30 // import the function into math.js 31 math.import({ 32 addIt: addIt 33 }) 34 35 // use the function via the expression parser 36 console.log('Using expression parser:') 37 console.log('2+4=' + math.evaluate('addIt(2, 4)')) 38 // This will output: 39 // 40 // input: a=2, b=4 41 // result: 6 42 // 2+4=6 43 44 // when used via plain JavaScript, the transform is not invoked 45 console.log('') 46 console.log('Using plain JavaScript:') 47 console.log('2+4=' + math.addIt(2, 4)) 48 // This will output: 49 // 50 // 6