Skip to content
This repository has been archived by the owner on May 23, 2019. It is now read-only.

Commit

Permalink
Fix bug with Expression.simplify
Browse files Browse the repository at this point in the history
Expression.simplify was failing when there was more than one term with
zero variables.
  • Loading branch information
nicolewhite committed Aug 21, 2015
1 parent 6b3fc01 commit 97aaf24
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
19 changes: 17 additions & 2 deletions src/expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Expression.prototype.simplify = function() {
}

copy._combineLikeTerms();
copy._moveTermsWithDegreeZeroToConstants();
copy._removeTermsWithCoefficientZero();
copy.constants = (copy.constant().valueOf() === 0 ? [] : [copy.constant()]);
copy._sort();
Expand Down Expand Up @@ -326,13 +327,27 @@ Expression.prototype._combineLikeTerms = function() {
this.terms.splice(j, 1);
}
}
}

return this;
};

Expression.prototype._moveTermsWithDegreeZeroToConstants = function() {
var keepTerms = [];
var constant = new Fraction(0, 1);

for (var i = 0; i < this.terms.length; i++) {
var thisTerm = this.terms[i];

if (thisTerm.variables.length === 0) {
this.constants.push(thisTerm.coefficient());
this.terms.splice(i, 1);
constant = constant.add(thisTerm.coefficient());
} else {
keepTerms.push(thisTerm);
}
}

this.constants.push(constant);
this.terms = keepTerms;
return this;
};

Expand Down
16 changes: 14 additions & 2 deletions test/expression-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -751,8 +751,20 @@ describe("Expression simplification", function() {
answer = answer.simplify(); // 12x + 33

expect(answer.toString()).toEqual("12x + 33");
})
});describe("Expression summation", function() {
});

it("should properly simplify if there are only constants", function() {
var exp = new Expression("x").add(3); // x + 3
exp = exp.pow(2, false); // xx + 3x + 3x + 3 * 3
exp = exp.eval({x: 2}, false); // 2 * 2 + 3 * 2 + 3 * 2 + 3 * 3

var ans = exp.simplify();

expect(ans.toString()).toEqual("25");
});
});

describe("Expression summation", function() {
it("should return a sum expressions whose variables have been substituted", function() {
var xplus3 = new Expression("x").add(3);
var ans = xplus3.summation(new Expression("x"), 3, 6);
Expand Down

0 comments on commit 97aaf24

Please sign in to comment.