|
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" |