1 | // objects
|
2 |
|
3 | // load math.js (using node.js)
|
4 | const { evaluate, format } = require('..')
|
5 |
|
6 | // create an object. Keys can be symbols or strings
|
7 | print(evaluate('{x: 2 + 1, y: 4}')) // {"x": 3, "y": 4}
|
8 | print(evaluate('{"name": "John"}')) // {"name": "John"}
|
9 |
|
10 | // create an object containing an object
|
11 | print(evaluate('{a: 2, b: {c: 3, d: 4}}')) // {"a": 2, "b": {"c": 3, "d": 4}}
|
12 |
|
13 | const scope = {
|
14 | obj: {
|
15 | prop: 42
|
16 | }
|
17 | }
|
18 |
|
19 | // retrieve properties using dot notation or bracket notation
|
20 | print(evaluate('obj.prop', scope)) // 42
|
21 | print(evaluate('obj["prop"]', scope)) // 42
|
22 |
|
23 | // set properties (returns the whole object, not the property value!)
|
24 | print(evaluate('obj.prop = 43', scope)) // 43
|
25 | print(evaluate('obj["prop"] = 43', scope)) // 43
|
26 | print(scope.obj) // {"prop": 43}
|
27 |
|
28 | /**
|
29 | * Helper function to output a value in the console. Value will be formatted.
|
30 | * @param {*} value
|
31 | */
|
32 | function print (value) {
|
33 | const precision = 14
|
34 | console.log(format(value, precision))
|
35 | }
|