Skip to content

Instantly share code, notes, and snippets.

@Kamisama666
Created December 19, 2018 19:18
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 Kamisama666/25f7b7e496d1057806a310cc04a0b362 to your computer and use it in GitHub Desktop.
Save Kamisama666/25f7b7e496d1057806a310cc04a0b362 to your computer and use it in GitHub Desktop.
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