Skip to content

Instantly share code, notes, and snippets.

@cjwinchester
Last active November 8, 2016 23:49
Show Gist options
  • Save cjwinchester/f214c29653839747e712eb20a2847b09 to your computer and use it in GitHub Desktop.
Save cjwinchester/f214c29653839747e712eb20a2847b09 to your computer and use it in GitHub Desktop.
Collapse an array of arrays of numeric pairs by consecutiveness, or whatever
// given an array of arrays of paired numbers (say, years)
// collapse consecutive into an aggregate human-readable string
// so like
// [[2001, 2002], [2002, 2003], [2003, 2004], [2015, 2016]]
// becomes "2001-2004, 2015-2016"
function makeHumanReadableYears(arr) {
var out = [];
var breakpoints = [];
var len = arr.length;
for (var i=0; i<len; i++) {
if (i > 0) {
if (arr[i][0] !== arr[i-1][1]) {
breakpoints.push(i);
}
} else {
breakpoints.push(0);
}
}
var breakpoints_len = breakpoints.length;
for (var x=0; x<breakpoints_len; x++) {
out.push(arr.slice(breakpoints[x], breakpoints[x+1]));
}
var str = [];
out.forEach(function(x, i) {
var flattened = [].concat.apply([], x);
var uniq = flattened.filter(function(x, i, a) {
return a.indexOf(x) === i;
}).sort();
var min = Math.min.apply(null, uniq);
var max = Math.max.apply(null, uniq);
str.push(min + "-" + max);
});
return str.join(", ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment