Skip to content

Instantly share code, notes, and snippets.

@s2tephen

s2tephen/binnify.js

Created Apr 21, 2016
Embed
What would you like to do?
Turn an array of integers (1, 2, 3, 4, 7, 9, 10) into a string of bins (1-4, 7, 9-10)
var binnify = function(arr) {
var output = [];
var bin_string = (arr) => (arr.length == 1) ? `${arr[0]}` : `${arr[0]}-${arr[arr.length - 1]}`;
var bin_start = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1] + 1) {
output.push(bin_string(arr.slice(bin_start, i)));
bin_start = i;
}
}
output.push(bin_string(arr.slice(bin_start)));
return output.join(', ');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment