UNPKG

1.52 kBJavaScriptView Raw
1// chaining
2
3// load math.js (using node.js)
4var 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
8var a = math.chain(3)
9 .add(4)
10 .multiply(2)
11 .done();
12print(a); // 14
13
14// Another example, calculate square(sin(pi / 4))
15var b = math.chain(math.pi)
16 .divide(4)
17 .sin()
18 .square()
19 .done();
20print(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
26var chain = math.chain(2).divide(3);
27var str = chain.toString();
28print(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().
33print(chain.valueOf()); // 0.66666666666667
34print(chain + 2); // 2.6666666666667
35
36
37// the function subset can be used to get or replace sub matrices
38var array = [[1, 2], [3, 4]];
39var v = math.chain(array)
40 .subset(math.index(1, 0))
41 .done();
42print(v); // 3
43
44var m = math.chain(array)
45 .subset(math.index(0, 0), 8)
46 .multiply(3)
47 .done();
48print(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 */
55function print (value) {
56 var precision = 14;
57 console.log(math.format(value, precision));
58}