Skip to content

Instantly share code, notes, and snippets.

@alexwilson
Last active December 4, 2016 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexwilson/41dfad8a31100fcfacb2f885fb93f004 to your computer and use it in GitHub Desktop.
Save alexwilson/41dfad8a31100fcfacb2f885fb93f004 to your computer and use it in GitHub Desktop.
// 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