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 | var math = require('../../index');
|
10 |
|
11 | // create a function
|
12 | function addIt(a, b) {
|
13 | return a + b;
|
14 | }
|
15 |
|
16 | // attach a transform function to the function addIt
|
17 | addIt.transform = function (a, b) {
|
18 | console.log('input: a=' + a + ', b=' + b);
|
19 | // we can manipulate the input arguments here before executing addIt
|
20 |
|
21 | var res = addIt(a, b);
|
22 |
|
23 | console.log('result: ' + res);
|
24 | // we can manipulate the result here before returning
|
25 |
|
26 | return res;
|
27 | };
|
28 |
|
29 | // import the function into math.js
|
30 | math.import({
|
31 | addIt: addIt
|
32 | });
|
33 |
|
34 | // use the function via the expression parser
|
35 | console.log('Using expression parser:');
|
36 | console.log('2+4=' + math.eval('addIt(2, 4)'));
|
37 | // This will output:
|
38 | //
|
39 | // input: a=2, b=4
|
40 | // result: 6
|
41 | // 2+4=6
|
42 |
|
43 | // when used via plain JavaScript, the transform is not invoked
|
44 | console.log('');
|
45 | console.log('Using plain JavaScript:');
|
46 | console.log('2+4=' + math.addIt(2, 4));
|
47 | // This will output:
|
48 | //
|
49 | // 6
|