Created
December 19, 2018 19:18
-
-
Save Kamisama666/25f7b7e496d1057806a310cc04a0b362 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
const unique = list => list.filter((value, index, list) => list.indexOf(value) === index); | |
const sortNumber = (a, b) => a - b; | |
const expandBlock = (accum, block) => { | |
if (block.indexOf('-') === -1) { | |
accum.push(parseInt(block)); | |
return accum; | |
} | |
const intervals = block.split('-').map(i => parseInt(i)).sort(sortNumber); | |
for (var i = intervals[0]; i <= intervals[intervals.length - 1]; i++) { | |
accum.push(i) | |
} | |
return accum; | |
} | |
const input = "3 , 7 - 10,4,6, 12-12, 1"; | |
const cleanInput = input.replace(/ /g, ""); | |
const matchPattern = /^((([1-9]\d*)|([1-9]\d*-[1-9]\d*))+,)+(([1-9]\d*)|([1-9]\d*-[1-9]\d*))+$|^[1-9]\d*$|^[1-9]\d*-[1-9]\d*$/; | |
if (!matchPattern.test(cleanInput)) { | |
throw new Error('The input has an invalid format'); | |
} | |
const blocks = cleanInput.split(','); | |
const numbers = blocks.reduce(expandBlock, []); | |
const output = unique(numbers).sort(sortNumber).join(','); | |
console.log(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment