Last active
April 21, 2016 00:32
-
-
Save knowtheory/a25a4599584741b5eecb401eab0cd791 to your computer and use it in GitHub Desktop.
This file contains 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
var elide = function(arr) { | |
// assume arr is sorted, or put it through a sort right here. | |
var tokens = []; // this'll be what gets output at the end. | |
var startOfRun = arr[0]; // pretend we have a stack. This is the first value pushed onto the stack. | |
var currentEndOfRun = startOfRun; // this is the top of our pretend stack. | |
var coalesce = function(start, end){ return "" + ((start != end) ? ""+start+"-"+end : start); } | |
// Consider each number in the array and it's relationship to the current run on the stack. | |
for (var i=1; i < arr.length; i++) { | |
// If the nextNumber is adjacent to the value at the top of the stack | |
var nextNumber = arr[i]; | |
if (nextNumber == currentEndOfRun + 1) { | |
// keep running! and push it onto the top of our pretend stack. | |
currentEndOfRun = arr[i]; | |
} else { | |
// otherwise, if the nextNumber isn't adjacent | |
// the previous run is complete. Coalesce the stack & push it into the tokens. | |
tokens.push(coalesce(startOfRun,currentEndOfRun)); | |
// clear the stack & push the nextNumber as the new start. | |
startOfRun = nextNumber; | |
currentEndOfRun = startOfRun; | |
} | |
} | |
tokens.push(coalesce(startOfRun,currentEndOfRun)); // flush the final token. | |
return tokens.join(', '); // join the tokens for the fun of it. | |
}; | |
console.log(elide([1,2,3,4,6,15,16,17,18,19,20,43])); // should print `1-4, 6, 15-20, 42` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment