I'm trying to extract contiguous elements from an outcome array and print their equivalent elements in a reference array. This is my test case:
it('should split into fragments', function() {
let ranges = getRanges({
reference: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
outcome: [true, true, false, false, true, false, false, true]
})
expect(ranges).to.eql([
['a b', true],
['c d', false],
['e', true],
['f g', false],
['h', true]
])
})
This works, but I'm wondering if there is a more elegant way of doing this:
function getRanges({reference, outcome}) {
function withinBoundsAndSameOutcome(i, currentOutcome) {
return i < outcome.length && outcome[i] == currentOutcome
}
let ranges = []
for (let i = 0; i < outcome.length; i++) {
let range = [reference[i]]
let currentOutcome = outcome[i]
while (withinBoundsAndSameOutcome(i + 1, currentOutcome)) {
i += 1
range.push(reference[i])
}
ranges.push([range.join(' '), currentOutcome])
}
return ranges
}