Guest User

Untitled

a guest
Nov 20th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. /**
  2. * Returns a sorted string of numbers, grouping consecutive numbers
  3. * of at least [range] _as_ a range of numbers, e.g. "8-11"
  4. * @param {Iterable<number>} collection Numbers to sort and group into ranges
  5. * @param {number} [range=2] min number of consecutive ints that form a range
  6. * @return {string}
  7. */
  8. function getSortedWithRanges(collection, range = 2) {
  9. // Roughly assert that we have an iterable
  10. // note: this doesn't validate the elements
  11. if (!(collection && typeof collection[Symbol.iterator] === 'function')) {
  12. throw new TypeError(
  13. `Expected [collection] to be an iterable,` +
  14. ` saw type "${Object.prototype.toString.call(collection)}"`
  15. );
  16. }
  17.  
  18. // Assert that the range is a finite number greater than 1
  19. if (!(Number.isFinite(range) && range > 1)) {
  20. throw new TypeError(
  21. `Expected [range] to be a finite number` +
  22. ` greater than 1, saw "${range}" of type "${typeof range}"`
  23. );
  24. }
  25.  
  26. const sorted = Array.from(collection).sort((a, b) => a - b);
  27.  
  28. // Bail early if we don't have enough elements to create ranges
  29. if (sorted.length < range) {
  30. return sorted.join();
  31. }
  32.  
  33. for (let i = 0; i < sorted.length; i++) {
  34. const n = sorted[i];
  35.  
  36. // Count of consecutive numbers found
  37. // offset by 1 so we skip checking the
  38. // current number
  39. let cursor = 1;
  40.  
  41. // Scan forward for said consecutive numbers
  42. while (sorted[i + cursor] === n + cursor) cursor++;
  43.  
  44. // If we found consective numbers that satisfy the min range,
  45. // splice it into the result and remove the elements that make
  46. // up the range
  47. if (cursor >= range) {
  48. sorted.splice(
  49. // Insertion index
  50. i,
  51. // Number of elements to be replaced with the range
  52. cursor,
  53. // Range to insert
  54. `${n}-${n + cursor - 1}`
  55. );
  56. } else if (cursor !== 1) {
  57. // Advance the index by however many consecutive
  58. // elements were found. We know we can't create a
  59. // range from them so it's safe to step over
  60. i += cursor - 1;
  61. }
  62. }
  63.  
  64. return sorted.join();
  65. }
  66.  
  67. // doit
  68. // const numbers = new Set([1, 2, 5, 9, 8, 7, 3, 4, 100]);
  69. // console.log(getSortedWithRanges(numbers, 4));
Add Comment
Please, Sign In to add comment