Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:40
Show Gist options
  • Save rfprod/b5815ab97f0295922bb78eae86d4a6a3 to your computer and use it in GitHub Desktop.
Save rfprod/b5815ab97f0295922bb78eae86d4a6a3 to your computer and use it in GitHub Desktop.
Extract Ranges from Sorted Integers List

Extract Ranges from Sorted Integers List

The function ranges(list) takes a sorted array of integers as input [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] and returns a string with ranges for the provided input "-6,-3-1,3-5,7-11,14,15,17-20". A range must consist of three item, i.e. [1, 2] is not considered a range. A range is formatted as A-B, e.g.: A = -7, B = -1, range is -7--1.

A script by V.

License.

function ranges(list) {
let output = [];
for (let i = 0, max = list.length; i < max; i++) {
const current = list[i];
let next = list[i + 1];
//console.log('current:', current);
if (Math.abs(current - next) !== 1 || !next) {
//console.log('next:', next);
//console.log('push current:', current);
output.push(current);
} else {
let nextNext = list[i + 2];
loop:
while (next || next === 0) {
//console.log('> select next:', next);
//console.log('> select nextNext:', nextNext);
if (Math.abs(next - nextNext) === 1) {
i++;
next = list[i + 1];
nextNext = list[i + 2];
} else {
if (Math.abs(current - next) !== 1) {
const item = current + '-' + next;
//console.log(' >> next > 0, push item:',item);
output.push(item);
} else {
//console.log('push current:',current,' then next:', next);
output.push(current);
output.push(next);
}
i++;
break loop;
}
}
}
}
return output.join(',');
}
// TEST
ranges([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]); // returns "-6,-3-1,3-5,7-11,14,15,17-20"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment