Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const howManyMonthsBetween = (from, to) => {
  2.   const fromDate = new Date(from)
  3.   const toDate = new Date(to)
  4.   const yearsBetween = toDate.getFullYear() - fromDate.getFullYear()
  5.  
  6.   return (yearsBetween * 12) + toDate.getMonth() - fromDate.getMonth()
  7. }
  8.  
  9. const useCreateDataArray = (results) => {
  10.   // sort array from earliest to latest
  11.   const chronological = results.sort((a, b) => {
  12.     return a.datetime > b.datetime
  13.   })
  14.  
  15.   const earliestEntryDate = new Date(chronological[0].datetime)
  16.   const latestEntryDate = new Date(chronological[chronological.length - 1].datetime)
  17.   const monthsBetween = howManyMonthsBetween(earliestEntryDate, latestEntryDate)
  18.  
  19.   // create object where:
  20.   //   keys: every possible month (in ms since 1970) from earliest to latest entries
  21.   //   values: how many reports occurred in that month (initialized to 0)
  22.   const initDataSeriesObj = Object.fromEntries(
  23.       [...Array(monthsBetween)].map((_, idx) => {
  24.         return [new Date(
  25.           earliestEntryDate.getFullYear(),
  26.           earliestEntryDate.getMonth() + idx,
  27.           1
  28.         ).getTime(), 0]
  29.       })
  30.   )
  31.  
  32.   const dataSeriesObj = chronological.reduce((acc, val) => {
  33.     const valAsDate = new Date(val.datetime)
  34.     const nearestMonth = new Date(valAsDate.getFullYear(), valAsDate.getMonth(), 1).getTime()
  35.     acc[nearestMonth]++
  36.     return acc
  37.   }, initDataSeriesObj)
  38.  
  39.   // return Object.entries(dataSeriesObj)
  40.   return Object.keys(dataSeriesObj).map((k) => [Number(k), dataSeriesObj[k]])
  41. }
  42.  
  43. export default useCreateDataArray
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement