Created
October 2, 2015 17:32
-
-
Save dwin/89f2fe99e504ed5693e5 to your computer and use it in GitHub Desktop.
Function that given a sorted array of page numbers, returns a string representing a book index. Combines consecutive pages to create ranges. Given [1,3,4,5,7,8,10] it should return the string “1, 3-5, 7-8, 10”.
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 arr = [1,2,3,5,8,10,11,12,15] | |
function bookIndex(arr) { | |
var temp = []; | |
for (var i = 0; i < arr.length; i++) { | |
if (arr[i]+1 == arr[i+1]) { | |
var start = arr[i]; | |
while (arr[i]+1 == arr[i+1]) { | |
i++; | |
} | |
var end = arr[i]; | |
temp.push(start + "-" + end); | |
} else { | |
temp.push(arr[i]); | |
} | |
} | |
var newstring = temp.join(','); | |
return newstring | |
} | |
console.log(bookIndex(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment