diff --git a/lib/function/algebra/simplify/simplifyCore.js b/lib/function/algebra/simplify/simplifyCore.js index b290fafc1..987807da5 100644 --- a/lib/function/algebra/simplify/simplifyCore.js +++ b/lib/function/algebra/simplify/simplifyCore.js @@ -49,6 +49,9 @@ function factory(type, config, load, typed, math) { if (type.isConstantNode(a1) && a1.value === "0") { return a0; } + if (node.args.length === 2 && type.isOperatorNode(a1) && a1.op === '-' && a1.fn === 'unaryMinus') { + return new OperatorNode('-', 'subtract', [a0,a1.args[0]]); + } return new OperatorNode(node.op, node.fn, a1 ? [a0,a1] : [a0]); } else if (node.op === "-") { if (type.isConstantNode(a0) && a1) { @@ -58,7 +61,7 @@ function factory(type, config, load, typed, math) { return new OperatorNode("-", "unaryMinus", [a1]); } } - if (node.fn === "subtract") { + if (node.fn === "subtract" && node.args.length === 2) { if (type.isConstantNode(a1) && a1.value === "0") { return a0; } @@ -67,8 +70,14 @@ function factory(type, config, load, typed, math) { } return new OperatorNode(node.op, node.fn, [a0,a1]); } else if (node.fn === "unaryMinus") { + if (type.isOperatorNode(a0)) { + if (a0.fn === 'unaryMinus') { + return a0.args[0]; + } + } return new OperatorNode(node.op, node.fn, [a0]); } + throw new Error('never happens'); } else if (node.op === "*") { if (type.isConstantNode(a0)) { if (a0.value === "0") { diff --git a/test/function/algebra/simplify.test.js b/test/function/algebra/simplify.test.js index 9e7c668bf..838e02a1a 100644 --- a/test/function/algebra/simplify.test.js +++ b/test/function/algebra/simplify.test.js @@ -53,6 +53,13 @@ describe('simplify', function() { assert.equal(fsimplified.eval()(5), 0.9933071490757153); }); + it('should simplifyCore convert +unaryMinus to subtract', function() { + simplifyAndCompareEval('--2', '2'); + var result = math.simplify('x + y + a', [math.simplify.simplifyCore], {a: -1}).toString() + assert.equal(result, "x + y - 1"); + }); + + it('should handle custom functions', function() { function doubleIt (x) { return x + x } var node = math.expression.node; @@ -137,9 +144,9 @@ describe('simplify', function() { }); it('should collect separated like factors', function() { + simplifyAndCompare('x*y*-x/(x^2)', '-y'); simplifyAndCompare('x/2*x', 'x^2/2'); simplifyAndCompare('x*2*x', '2*x^2'); - simplifyAndCompare('x*y*-x/(x^2)', '-y'); }); it('should handle non-existing functions like a pro', function() {