Skip to content

Commit

Permalink
created convertSubToAdd function
Browse files Browse the repository at this point in the history
  • Loading branch information
mankal111 committed Dec 19, 2018
1 parent 02a801f commit 3e4618f
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions src/reducers/expressionUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,38 @@ import math from 'mathjs';

export const getTrimmedPath = path => path.replace(/Root?./, '');

export const convertSubToAdd = (node) => {
let convertedNode = node.cloneDeep();
if (convertedNode.args[1].type === 'ConstantNode') {
convertedNode.args[1] = new math.expression.node.ConstantNode(-convertedNode.args[1].value);
}
convertedNode = new math.expression.node.OperatorNode(
'+',
'add',
[convertedNode.args[0], convertedNode.args[1]],
);
return convertedNode;
};

export const performActionOnTree = (state, actionName) => {
const newTree = state.expressionTree.cloneDeep();
const selectedPath = getTrimmedPath(state.selectedExpressionPath);
const selectedNode = state.selectedExpressionNode;
let newNode = selectedNode;
let newNode = selectedNode.cloneDeep();
switch (actionName) {
case 'commutate':
// mathjs creates a subtraction operation,
// which causes problem in operation commutation (1-2=2-1)
// so if the operation is subtraction, we turn it to addition
// and negate the second operant before the commutation
if (selectedNode.fn === 'subtract') {
if (selectedNode.args[1].type === 'ConstantNode') {
selectedNode.args[1] = new math.expression.node.ConstantNode(-selectedNode.args[1].value);
}
newNode = new math.expression.node.OperatorNode(
'+',
'add',
[selectedNode.args[1], selectedNode.args[0]],
);
} else {
newNode = new math.expression.node.OperatorNode(
selectedNode.op,
selectedNode.fn,
[selectedNode.args[1], selectedNode.args[0]],
);
newNode = convertSubToAdd(selectedNode);
}
newNode = new math.expression.node.OperatorNode(
newNode.op,
newNode.fn,
[newNode.args[1], newNode.args[0]],
);
break;
case 'evaluate':
newNode = new math.expression.node.ConstantNode(selectedNode.eval());
Expand Down

0 comments on commit 3e4618f

Please sign in to comment.