在这里,我还包括了一个基本的测试用例:
var tests = [
[1,2,3,4,5,6,7,9],
[1,2,3,4,5,6,7,12,13,14,15,16,20],
[1,2,3,4,5,6,7,12,13,14,15,16,20,21,22,23],
[1,2,3,4,5,6,7,120,13,14,15,16,2890,21,22,23],
[1,2,3,4,8,9,10,11,12,14,16,18,20,21,22,23,30,31,34]
];
var processArray = function(arr, sep) {
var l = arr.length, i, sl, res = [], succ = [];
for (i = 0; i < l; i++) {
var c = (i != 0 && (arr[i - 1] + 1 !== arr[i]));
if ((i == l - 1) || c) {
if (!c) succ.push(arr[i]);
if ((sl = succ.length) > 0) {
res.push(succ[0] + sep + succ[sl - 1]);
succ = [];
}
if (arr[i + 1] - 1 === arr[i]) {
succ.push(arr[i])
} else if (c) {
res.push(arr[i]);
}
} else {
succ.push(arr[i]);
}
}
return res;
}
// setup
for (var i = 0; i < tests.length; i++) {
console.log('Test ' + i + ' : { ' + processArray(tests[i], ' to ').join('; ') + ' }');
}
这是小提琴