Skip to content

Instantly share code, notes, and snippets.

@developandbehappy
Created February 17, 2019 17:22
Show Gist options
  • Select an option

  • Save developandbehappy/024f9eb8becab6cdca30602141c14f5a to your computer and use it in GitHub Desktop.

Select an option

Save developandbehappy/024f9eb8becab6cdca30602141c14f5a to your computer and use it in GitHub Desktop.
function compressed(arr) {
const sortedArr = arr.sort((a, b) => a - b);
let result = "";
let isAdding = false;
let latestLoop = false;
for (let i = 0; i < sortedArr.length; i++) {
const resultElement = sortedArr[i];
const nextResult = sortedArr[i + 1];
if ( nextResult === undefined) {
latestLoop = true;
result += resultElement;
}
if (resultElement + 1 === nextResult && !isAdding && !latestLoop) { // the first init
result += resultElement;
result += "-";
isAdding = true;
}
if (isAdding && resultElement + 1 !== nextResult && !latestLoop) { // last element
result += resultElement;
result += ",";
isAdding = false;
}
if (!isAdding && resultElement + 1 !== nextResult && !latestLoop) {
result += resultElement;
result += ",";
}
}
return result;
}
console.log(compressed([3, 2, 1, 5, 6, -1, 10]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment