UNPKG

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