UNPKG

1.48 kBJavaScriptView Raw
1// chaining
2
3// load math.js (using node.js)
4const math = require('..')
5
6// create a chained operation using the function `chain(value)`
7// end a chain using done(). Let's calculate (3 + 4) * 2
8const a = math.chain(3)
9 .add(4)
10 .multiply(2)
11 .done()
12print(a) // 14
13
14// Another example, calculate square(sin(pi / 4))
15const 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
26const chain = math.chain(2).divide(3)
27const 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// the function subset can be used to get or replace sub matrices
37const array = [[1, 2], [3, 4]]
38const v = math.chain(array)
39 .subset(math.index(1, 0))
40 .done()
41print(v) // 3
42
43const m = math.chain(array)
44 .subset(math.index(0, 0), 8)
45 .multiply(3)
46 .done()
47print(m) // [[24, 6], [9, 12]]
48
49/**
50 * Helper function to output a value in the console. Value will be formatted.
51 * @param {*} value
52 */
53function print (value) {
54 const precision = 14
55 console.log(math.format(value, precision))
56}