simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

chaining.js (1475B)


      1 // chaining
      2 
      3 // load math.js (using node.js)
      4 const 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
      8 const 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 const 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 const chain = math.chain(2).divide(3)
     27 const 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 // the function subset can be used to get or replace sub matrices
     37 const array = [[1, 2], [3, 4]]
     38 const v = math.chain(array)
     39   .subset(math.index(1, 0))
     40   .done()
     41 print(v) // 3
     42 
     43 const m = math.chain(array)
     44   .subset(math.index(0, 0), 8)
     45   .multiply(3)
     46   .done()
     47 print(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  */
     53 function print (value) {
     54   const precision = 14
     55   console.log(math.format(value, precision))
     56 }