Guest User

Untitled

a guest
Feb 22nd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. // [1, 3, 5, 7, 8, 11, 12, 13, 20] -> 1,3,5,7-8,11-13,20
  2. function short(arr) {
  3. var sorted = arr.sort(function (a, b) {
  4. if (a < b) { return -1; }
  5. else if (a > b) { return 1; }
  6. else { return 0; }
  7. });
  8.  
  9. function add(res, newValue) {
  10. var last = res[res.length-1];
  11. if (!last) {
  12. res.push([newValue]);
  13. return;
  14. }
  15.  
  16. var [firstItem, lastItem] = last;
  17. if (firstItem && lastItem) {
  18. if (lastItem+1 === newValue) {
  19. last[last.length-1] = newValue;
  20. } else {
  21. res.push([newValue]);
  22. }
  23. } else if (firstItem) {
  24. if (firstItem + 1 === newValue) {
  25. last.push(newValue);
  26. } else {
  27. res.push([newValue]);
  28. }
  29. } else {
  30. last.push(newValue);
  31. }
  32. }
  33.  
  34. return sorted
  35. .reduce(function (res, currentItem) {
  36. add(res, currentItem);
  37.  
  38. return res;
  39. }, [])
  40. .map(function (minMax) {
  41. return minMax.join('-');
  42. })
  43. .join(',');
  44. }
  45.  
  46. short([1, 3, 5, 7, 8, 11, 12, 13, 20]);
Add Comment
Please, Sign In to add comment