-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathIndexNode.js
More file actions
241 lines (213 loc) · 7.89 KB
/
IndexNode.js
File metadata and controls
241 lines (213 loc) · 7.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { map } from '../../utils/array.js'
import { getSafeProperty } from '../../utils/customs.js'
import { factory } from '../../utils/factory.js'
import { isArray, isConstantNode, isMatrix, isNode, isString, typeOf } from '../../utils/is.js'
import { escape } from '../../utils/string.js'
const name = 'IndexNode'
const dependencies = [
'Node',
'size'
]
export const createIndexNode = /* #__PURE__ */ factory(name, dependencies, ({ Node, size }) => {
class IndexNode extends Node {
/**
* @constructor IndexNode
* @extends Node
*
* Describes a subset of a matrix or an object property.
* Cannot be used on its own, needs to be used within an AccessorNode or
* AssignmentNode.
*
* @param {Node[]} dimensions
* @param {boolean} [dotNotation=false]
* Optional property describing whether this index was written using dot
* notation like `a.b`, or using bracket notation like `a["b"]`
* (which is the default). This property is used for string conversion.
*/
constructor (dimensions, dotNotation) {
super()
this.dimensions = dimensions
this.dotNotation = dotNotation || false
// validate input
if (!Array.isArray(dimensions) || !dimensions.every(isNode)) {
throw new TypeError(
'Array containing Nodes expected for parameter "dimensions"')
}
if (this.dotNotation && !this.isObjectProperty()) {
throw new Error('dotNotation only applicable for object properties')
}
}
static name = name
get type () { return name }
get isIndexNode () { return true }
/**
* Compile a node into a JavaScript function.
* This basically pre-calculates as much as possible and only leaves open
* calculations which depend on a dynamic scope with variables.
* @param {Object} math Math.js namespace with functions and constants.
* @param {Object} argNames An object with argument names as key and `true`
* as value. Used in the SymbolNode to optimize
* for arguments from user assigned functions
* (see FunctionAssignmentNode) or special symbols
* like `end` (see IndexNode).
* @return {function} Returns a function which can be called like:
* evalNode(scope: Object, args: Object, context: *)
*/
_compile (math, argNames) {
// TODO: implement support for bignumber (currently bignumbers are silently
// reduced to numbers when changing the value to zero-based)
// TODO: Optimization: when the range values are ConstantNodes,
// we can beforehand resolve the zero-based value
// optimization for a simple object property
const evalDimensions = map(this.dimensions, function (dimension, i) {
const needsEnd = dimension
.filter(node => node.isSymbolNode && node.name === 'end')
.length > 0
if (needsEnd) {
// SymbolNode 'end' is used inside the index,
// like in `A[end]` or `A[end - 2]`
const childArgNames = Object.create(argNames)
childArgNames.end = true
const _evalDimension = dimension._compile(math, childArgNames)
return function evalDimension (scope, args, context) {
if (!isMatrix(context) && !isArray(context) && !isString(context)) {
throw new TypeError(
'Cannot resolve "end": ' +
'context must be a Matrix, Array, or string but is ' +
typeOf(context))
}
const s = size(context)
const childArgs = Object.create(args)
childArgs.end = s[i]
return _evalDimension(scope, childArgs, context)
}
} else {
// SymbolNode `end` not used
return dimension._compile(math, argNames)
}
})
const index = getSafeProperty(math, 'index')
return function evalIndexNode (scope, args, context) {
const dimensions = map(evalDimensions, function (evalDimension) {
return evalDimension(scope, args, context)
})
return index(...dimensions)
}
}
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
forEach (callback) {
for (let i = 0; i < this.dimensions.length; i++) {
callback(this.dimensions[i], 'dimensions[' + i + ']', this)
}
}
/**
* Create a new IndexNode whose children are the results of calling
* the provided callback function for each child of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {IndexNode} Returns a transformed copy of the node
*/
map (callback) {
const dimensions = []
for (let i = 0; i < this.dimensions.length; i++) {
dimensions[i] = this._ifNode(
callback(this.dimensions[i], 'dimensions[' + i + ']', this))
}
return new IndexNode(dimensions, this.dotNotation)
}
/**
* Create a clone of this node, a shallow copy
* @return {IndexNode}
*/
clone () {
return new IndexNode(this.dimensions.slice(0), this.dotNotation)
}
/**
* Test whether this IndexNode contains a single property name
* @return {boolean}
*/
isObjectProperty () {
return this.dimensions.length === 1 &&
isConstantNode(this.dimensions[0]) &&
typeof this.dimensions[0].value === 'string'
}
/**
* Returns the property name if IndexNode contains a property.
* If not, returns null.
* @return {string | null}
*/
getObjectProperty () {
return this.isObjectProperty() ? this.dimensions[0].value : null
}
/**
* Get string representation
* @param {Object} options
* @return {string} str
*/
_toString (options) {
// format the parameters like "[1, 0:5]"
return this.dotNotation
? ('.' + this.getObjectProperty())
: ('[' + this.dimensions.join(', ') + ']')
}
/**
* Get a JSON representation of the node
* @returns {Object}
*/
toJSON () {
return {
mathjs: name,
dimensions: this.dimensions,
dotNotation: this.dotNotation
}
}
/**
* Instantiate an IndexNode from its JSON representation
* @param {Object} json
* An object structured like
* `{"mathjs": "IndexNode", dimensions: [...], dotNotation: false}`,
* where mathjs is optional
* @returns {IndexNode}
*/
static fromJSON (json) {
return new IndexNode(json.dimensions, json.dotNotation)
}
/**
* Get HTML representation
* @param {Object} options
* @return {string} str
*/
_toHTML (options) {
// format the parameters like "[1, 0:5]"
const dimensions = []
for (let i = 0; i < this.dimensions.length; i++) {
dimensions[i] = this.dimensions[i].toHTML()
}
if (this.dotNotation) {
return '<span class="math-operator math-accessor-operator">.</span>' +
'<span class="math-symbol math-property">' +
escape(this.getObjectProperty()) + '</span>'
} else {
return '<span class="math-parenthesis math-square-parenthesis">[</span>' +
dimensions.join('<span class="math-separator">,</span>') +
'<span class="math-parenthesis math-square-parenthesis">]</span>'
}
}
/**
* Get LaTeX representation
* @param {Object} options
* @return {string} str
*/
_toTex (options) {
const dimensions = this.dimensions.map(function (range) {
return range.toTex(options)
})
return this.dotNotation
? ('.' + this.getObjectProperty() + '')
: ('_{' + dimensions.join(',') + '}')
}
}
return IndexNode
}, { isClass: true, isNode: true })