Created
February 17, 2019 17:22
-
-
Save developandbehappy/024f9eb8becab6cdca30602141c14f5a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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