Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. var equation = ["+2x", "+1y", "-1x", "+2y"];
  2. var equationRegex = /[a-zA-Z].*/g;
  3. var numberRegex = /\+([^;]*)[a-zA-z]/g; // Make this the right regex, should match the number part and the sign e.g +3.5
  4.  
  5. function sortEquation(a, b) {
  6. var valueA = a.match(equationRegex)[0];
  7. var valueB = b.match(equationRegex)[0];
  8.  
  9. if (valueA < valueB) {
  10. return -1;
  11. }
  12. if (valueA > valueB) {
  13. return 1;
  14. }
  15. // a must be equal to b
  16. return 0;
  17. }
  18.  
  19.  
  20. function reduceEquation (accumulator, currentValue, i, array) {
  21. var prevValue = array[i-1];
  22. var splitCurrentValue = currentValue.match(equationRegex);
  23. var splitPreviousValue = prevValue.match(equationRegex);
  24.  
  25. var splitCurrentNumber = currentValue.match(numberRegex);
  26. var splitPreviousNumber = prevValue.match(numberRegex);
  27.  
  28. if(splitCurrentValue[0] === splitPreviousValue[0]) {
  29. var total = Number(splitCurrentNumber[0]) + Number(splitPreviousNumber[0]);
  30. var signedTotal = total > 0 ? "+" + total : String(total);
  31.  
  32. return signedTotal + splitCurrentValue[1];
  33. }
  34.  
  35. return accumulator;
  36. }
  37.  
  38. var finalAnswer = equation
  39. .sort(sortEquation)
  40. .reduce(reduceEquation);
  41.  
  42. console.log(finalAnswer + " = 0");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement