Skip to content

Instantly share code, notes, and snippets.

@L00Cyph3r
Last active October 5, 2018 08:21
Show Gist options
  • Save L00Cyph3r/e794c01c2aafa7680a31e7fc4d414a49 to your computer and use it in GitHub Desktop.
Save L00Cyph3r/e794c01c2aafa7680a31e7fc4d414a49 to your computer and use it in GitHub Desktop.
Stringify list of numbers into a number-range like in a book
/**
* Originally from: https://stackoverflow.com/a/24104156
* Rewritten in JavaScript
*/
var pagenumbers = [
10,12,13,45,46,47,48,49,50,3,4,5
];
function rangeToString(items) {
items.sort(function (a, b) {
return a - b;
});
var point = null;
var range = false;
var string = '';
for (var i = 0; i < items.length; i++) {
if (point === items[i]) {
continue;
}
if (point === null) {
string = string + items[i];
} else if ((point + 1) === items[i]) {
range = true;
} else {
if (range === true) {
string = string + '-' + point;
}
string = string + ',' + items[i];
}
point = items[i];
}
if (range === true) {
string = string + '-' + point;
}
return string;
}
var string = rangeToString(pagenumbers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment