JSFiddle - React, Tailwind, and code Playground
by Sergei Sokolov
CSS
output {
font-family: Courier New, monospace
}
JavaScript
/**
* для вопроса https://toster.ru/q/691925
* Как вам такое решение задачки?
*/
const zip = arr => {
return arr.reduce((agg, c) => {
const iR = agg.indexOf(c + 1);
const iL = agg.lastIndexOf(c - 1);
if (!!~iR && !!~iL) agg.splice(iL, 2);
else if (!!~iR) agg[iR] = c;
else if (!!~iL) agg[iL] = c;
else {
let pos = 0;
while (pos < agg.length && agg[pos] < c) pos++;
agg.splice(pos, 0, c, c);
}
return agg;
}, [])
.reduce((agg, c, i, arr) => {
if (!(i&1)) agg.push(arr[i+1] === c ? c : [c, arr[i+1]].join('-'));
return agg;
}, [])
.join(', ')
}
const tests = [
[1, 4, 5, 2, 3, 9, 8, 11, 0],
[1, 4, 3, 2],
[1, 4],
[],
null,
];
const output = document.querySelector("output");
tests.forEach(test => output.innerHTML += JSON.stringify(test) + ': "' + zip(test) + '"<br>')