Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // [1, 3, 5, 7, 8, 11, 12, 13, 20] -> 1,3,5,7-8,11-13,20
- function short(arr) {
- var sorted = arr.sort(function (a, b) {
- if (a < b) { return -1; }
- else if (a > b) { return 1; }
- else { return 0; }
- });
- function add(res, newValue) {
- var last = res[res.length-1];
- if (!last) {
- res.push([newValue]);
- return;
- }
- var [firstItem, lastItem] = last;
- if (firstItem && lastItem) {
- if (lastItem+1 === newValue) {
- last[last.length-1] = newValue;
- } else {
- res.push([newValue]);
- }
- } else if (firstItem) {
- if (firstItem + 1 === newValue) {
- last.push(newValue);
- } else {
- res.push([newValue]);
- }
- } else {
- last.push(newValue);
- }
- }
- return sorted
- .reduce(function (res, currentItem) {
- add(res, currentItem);
- return res;
- }, [])
- .map(function (minMax) {
- return minMax.join('-');
- })
- .join(',');
- }
- short([1, 3, 5, 7, 8, 11, 12, 13, 20]);
Add Comment
Please, Sign In to add comment