JSFiddle - React, Tailwind, and code Playground

by Graham Dixon

JavaScript

// Get the week number of a date relative of its year
const getWeek = function(date) {
  // clear the time set on the date
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1
  const week1 = new Date(date.getFullYear(), 0, 4);

  // adjust to Thursday in week 1 and count number of weeks from date to week1
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

// Group by time period - Commits by day | week | month | year
const groupByTimePeriods = function(obj, timestamp) {
  // store everything into res
  const res = {};
  // defines length of a single day in milliseconds
  const oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
  for (let i = 0; i < obj.length; i++) {
    // convert epoch to milliseconds and create a date obj
    const d = new Date(obj[i][timestamp] * 1000);
    // get day of the week (0-6) 0 is Sunday
    const day = d.getDay();
    // establish which week where we're on (0-50) 0 is first week of Jan
    const week = getWeek(d);
    // get the month number (0-11) 0 is January
    const month = d.getMonth();
    // get the full year (2019)
    const year = d.getFullYear();

    // define object keys if absent
    res[year] = res[year] || {};
    res[year][month] = res[year][month] || {};
    res[year][month][week] = res[year][month][week] || {};
    res[year][month][week][day] = res[year][month][week][day] || [];
    res[year][month][week][day].push(obj[i]);
  }

  // return complete object sorted into year->month->week->day
  return res;
};

const eventsArray = [{ id: 1, date: 1317906596 }, { id: 2, date: 1317908605 }, { id: 3, date: 1317909229 }, { id: 4, date: 1317909478 }, { id: 5, date: 1317909832 }, { id: 6, date: 1317979141 }, { id: 7, date: 1317979232 }, { id: 8, date: 1317986965 }, { id: 9, date: 1318582119 }, { id: 10, date: 1318595862...