Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. /**
  2. * @function findDateRanges
  3. * @description Find and group date-ranges in an Array of dates
  4. *
  5. * @param {Array} sourceCollection - containing ISODateStrings in any order
  6. * @param {?Array} destinationCollection - defaults to []
  7. *
  8. * @returns {Array} - ^destinationCollection passed or new Array
  9. *
  10. * @example findDateRanges([
  11. * '2001-01-07T07:07:07.070Z',
  12. * '2001-01-04T04:04:04.040Z',
  13. * '2001-01-04T04:02:04.016Z',
  14. * '2001-01-02T02:02:02.020Z',
  15. * '2001-01-01T01:01:01.010Z'
  16. * ]) --> [ // As Date Objects:
  17. * [ 1/1/2001, 1/2/2001 ],
  18. * [ 1/4/2001, 1/4/2001 ],
  19. * [ 1/7/2001 ] }
  20. * ]
  21. */
  22. const findDateRanges = (sourceCollection, destinationCollection=[]) => {
  23. const toDate = dateString => new Date(dateString);
  24. const datesObjsSortedAsc = [].concat(sourceCollection).map(toDate).sort((a, b) => a === b ? 0 : a > b ? 1 : -1);
  25. for (let i = 0, l = datesObjsSortedAsc.length, a, d, p, pd; i < l; i++) {
  26. a = function addToRange() {
  27. p = [];
  28. p.push(d);
  29. destinationCollection.push(p);
  30. };
  31. d = toDate(datesObjsSortedAsc[i]); // Date as Date Object
  32. if (p) { // Has p (previous-range)
  33. pd = p[p.length - 1]; // Previous-date
  34. // Determine if date is part of range
  35. if (
  36. d.getUTCFullYear() === pd.getUTCFullYear() && // Same year
  37. d.getUTCMonth() === pd.getUTCMonth() && // Same month
  38. ([ 0, -1 ].indexOf(pd.getUTCDate() - d.getUTCDate()) > -1) // 0-1 day later (duplicate date handling)
  39. ) {
  40. // Part of range
  41. p.push(d);
  42. } else {
  43. // New range
  44. a();
  45. }
  46. } else {
  47. // Initial loop iteration
  48. a();
  49. }
  50. }
  51. return destinationCollection;
  52. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement