Last active
December 4, 2016 14:41
-
-
Save alexwilson/41dfad8a31100fcfacb2f885fb93f004 to your computer and use it in GitHub Desktop.
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
// Reduce a list by cancelling pairs of values. | |
// e.g. cancelByPair('LLLRLRLRLR', 'L', 'R') === 'LL' | |
function cancelByPair(list, firstValue, secondValue) { | |
// First filter out all of these values, and count them as we go. | |
let count = 0; | |
const cancelledList = list.filter(c => { | |
switch (c) { | |
case firstValue: | |
count++ | |
return false | |
case secondValue: | |
count-- | |
return false | |
default: | |
return true | |
} | |
}) | |
// Now, use the count to rebuild the list with the surplus value. | |
.concat( | |
// Construct an array of the size of count, so we may iterate. | |
Array.from(Array(Math.abs(count)).keys()) | |
// If count is greater than zero, we know we removed too many of the first value. | |
.map(_ => count >= 0 ? firstValue : secondValue)) | |
return cancelledList | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment