Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var equation = ["+2x", "+1y", "-1x", "+2y"];
- var equationRegex = /[a-zA-Z].*/g;
- var numberRegex = /\+([^;]*)[a-zA-z]/g; // Make this the right regex, should match the number part and the sign e.g +3.5
- function sortEquation(a, b) {
- var valueA = a.match(equationRegex)[0];
- var valueB = b.match(equationRegex)[0];
- if (valueA < valueB) {
- return -1;
- }
- if (valueA > valueB) {
- return 1;
- }
- // a must be equal to b
- return 0;
- }
- function reduceEquation (accumulator, currentValue, i, array) {
- var prevValue = array[i-1];
- var splitCurrentValue = currentValue.match(equationRegex);
- var splitPreviousValue = prevValue.match(equationRegex);
- var splitCurrentNumber = currentValue.match(numberRegex);
- var splitPreviousNumber = prevValue.match(numberRegex);
- if(splitCurrentValue[0] === splitPreviousValue[0]) {
- var total = Number(splitCurrentNumber[0]) + Number(splitPreviousNumber[0]);
- var signedTotal = total > 0 ? "+" + total : String(total);
- return signedTotal + splitCurrentValue[1];
- }
- return accumulator;
- }
- var finalAnswer = equation
- .sort(sortEquation)
- .reduce(reduceEquation);
- console.log(finalAnswer + " = 0");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement