1 | // chaining
|
2 |
|
3 | // load math.js (using node.js)
|
4 | var math = require('../index');
|
5 |
|
6 | // create a chained operation using the function `chain(value)`
|
7 | // end a chain using done(). Let's calculate (3 + 4) * 2
|
8 | var a = math.chain(3)
|
9 | .add(4)
|
10 | .multiply(2)
|
11 | .done();
|
12 | print(a); // 14
|
13 |
|
14 | // Another example, calculate square(sin(pi / 4))
|
15 | var b = math.chain(math.pi)
|
16 | .divide(4)
|
17 | .sin()
|
18 | .square()
|
19 | .done();
|
20 | print(b); // 0.5
|
21 |
|
22 | // A chain has a few special methods: done, toString, valueOf, get, and set.
|
23 | // these are demonstrated in the following examples
|
24 |
|
25 | // toString will return a string representation of the chain's value
|
26 | var chain = math.chain(2).divide(3);
|
27 | var str = chain.toString();
|
28 | print(str); // "0.6666666666666666"
|
29 |
|
30 | // a chain has a function .valueOf(), which returns the value hold by the chain.
|
31 | // This allows using it in regular operations. The function valueOf() acts the
|
32 | // same as function done().
|
33 | print(chain.valueOf()); // 0.66666666666667
|
34 | print(chain + 2); // 2.6666666666667
|
35 |
|
36 |
|
37 | // the function subset can be used to get or replace sub matrices
|
38 | var array = [[1, 2], [3, 4]];
|
39 | var v = math.chain(array)
|
40 | .subset(math.index(1, 0))
|
41 | .done();
|
42 | print(v); // 3
|
43 |
|
44 | var m = math.chain(array)
|
45 | .subset(math.index(0, 0), 8)
|
46 | .multiply(3)
|
47 | .done();
|
48 | print(m); // [[24, 6], [9, 12]]
|
49 |
|
50 |
|
51 | /**
|
52 | * Helper function to output a value in the console. Value will be formatted.
|
53 | * @param {*} value
|
54 | */
|
55 | function print (value) {
|
56 | var precision = 14;
|
57 | console.log(math.format(value, precision));
|
58 | }
|