Created
January 18, 2017 06:09
-
-
Save jamsea/bdda739f394d0b1d8e4b30813fcda088 to your computer and use it in GitHub Desktop.
Sorty stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment