This repository was archived by the owner on Aug 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathindex.js
More file actions
60 lines (53 loc) · 1.76 KB
/
index.js
File metadata and controls
60 lines (53 loc) · 1.76 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
const ChangeTypes = require('../../ChangeTypes');
const Node = require('../../node');
const TreeSearch = require('../../TreeSearch');
// Searches through the tree, prioritizing deeper nodes, and substitutes
// in-scope values for their respective expressions on a symbol node if possible.
// Returns a Node.Status object.
const search = TreeSearch.postOrder(scopeSubstitution);
function scopeSubstitution(node, options={}) {
if (Node.Type.isSymbol(node)) {
return substituteAndSimplifySymbols(node, options);
}
else {
return Node.Status.noChange(node);
}
}
// SUBSTITUTES
// Returns a Node.Status object with substeps
function substituteAndSimplifySymbols(node, options={}) {
if (!options.hasOwnProperty('scope')) {
return Node.Status.noChange(node);
}
if (!Node.Type.isSymbol(node)) {
return Node.Status.noChange(node);
}
let symbolName;
if (node.type === 'SymbolNode') {
symbolName = node.name;
}
else if (Node.Type.isUnaryMinus(node)) {
symbolName = node.args[0].name;
}
const scope = options.scope;
if (scope.hasOwnProperty(symbolName)) {
// when declared at top, kept getting
// TypeError: <nameIGaveToFunction> is not a function
const simplifyExpression = require('../../simplifyExpression');
const substeps = simplifyExpression(scope[symbolName]);
if (substeps.length === 0) {
const newNode = Node.Creator.constant(Number(scope[symbolName]));
return Node.Status.nodeChanged(
ChangeTypes.SUBSTITUTE_SCOPE_SYMBOL, node, newNode);
}
else {
const newNode = substeps.slice(-1)[0].newNode;
return Node.Status.nodeChanged(
ChangeTypes.SUBSTITUTE_SCOPE_SYMBOL, node, newNode, false, substeps);
}
}
else {
return Node.Status.noChange(node);
}
}
module.exports = search;