Skip to content

Instantly share code, notes, and snippets.

@wopian
Created September 1, 2018 20:49
Show Gist options
  • Save wopian/befa0be7458735d66b5da535afc9942f to your computer and use it in GitHub Desktop.
Save wopian/befa0be7458735d66b5da535afc9942f to your computer and use it in GitHub Desktop.
Expand '1-2,4-5' to '1,2,4,5' and print numbers missing in sequence
const { assert, log } = console
const input = '1-2,4-6'
const output = '1,2,4,5,6'
const outputMissing = '3'
const numericSort = (a, b) => a - b
function expandRange (string) {
return String(string.split(',').reduce(function (r, a) {
var b = a.split('-').map(Number)
do {
r.push(b[0])
b[0]++
} while (b[0] <= b[1])
return r
}, []))
}
log(expandRange(input))
assert(expandRange(input) === output, `Got "${expandRange(input)}" expected "${output}"`)
const missingVolumesReduce = (missing, val, i, arr) => {
const previous = i - 1
const diff = val - arr[previous]
if (diff < 1) return []
let j = 1
while (j < diff) {
missing.push(arr[previous] + j)
j++
}
return missing
}
function missingVolumes (string) {
return String(`0,${string}`
.split(',')
.map(Number)
.sort(numericSort)
.reduce(missingVolumesReduce, []))
}
log(missingVolumes(expandRange(input)))
assert(missingVolumes(expandRange(input)) === outputMissing, `Got "${missingVolumes(expandRange(input))}" expected "${outputMissing}"`)
// 1-2,3,4-5
// 1,2,3,4,5
// assert(true === false, "Hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment