Q192112
by iori horigome
HTML
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
JavaScript
const MAX_LENGTH = 100000;
const f = ary => {
const len = ary.length;
if (len > MAX_LENGTH) {
throw new Error('too long !');
}
if (len <= 1){
return [ary];
}
const head = [ary[0]];
let tailIndex = -1; //?
for (let i=1; i < len; i++) {
if (ary[i-1] + 1 === ary[i]) {
head.push(ary[i])
} else {
tailIndex = i;
break;
}
}
return tailIndex === -1 ? [ head ] : [ head ].concat(f(ary.slice(tailIndex)));
};
const data = [1,2,3,6,7,9,25,26,27,30];
const result = f(data);
console.log(result);
console.log(result.map(e => e.length >=2 ? `${e[0]}〜${e[e.length-1]}` : `${e[0]}`));