-2

I am trying to a function generateIntervals that takes a startTime (seconds), endTime (seconds) and a frequency being either minute, hour or day and it returns an array of sub arrays of intervals divided by that frequency. For example:

generateIntervals(0, 60, 'minute') // [[0, 59], [60, 60]]
generateIntervals(0, 200, 'hour') // [[0, 200]]

Here is my attempt:


const intervalMap = {
  minute: 60,
  hour: 3600,
  day: 86400,
}


function generateIntervals(startTime, endTime, frequency) {
  const interval = intervalMap[frequency] - 1
  const chunked = []
  let curr = startTime

  while (curr <= endTime) {
    const end = Math.min(endTime, curr + interval)
    chunked.push([curr, end])
    curr = end + 1
  }

  return chunked
}

I works but I wonder if there is a cleaner way for doing that? maybe a more functional way?

Joji
  • 4,703
  • 7
  • 41
  • 86
  • Does this answer your question? [Does JavaScript have a method like "range()" to generate a range within the supplied bounds?](https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp) – TheEagle Sep 16 '22 at 23:12
  • 1
    Your "working" code produces an error on this line `const end = Math.min(end, curr + interval)`. You are referencing `end` on the right side, while it has not been initialised yet. – trincot Sep 16 '22 at 23:15
  • @Programmer no it doesn't – Joji Sep 16 '22 at 23:36

1 Answers1

1

Your code is fine provided you fix this line:

const end = Math.min(end, curr + interval)

to:

const end = Math.min(endTime, curr + interval)

Here is an alternative that has a more functional programming style:

function generateIntervals(startTime, endTime, frequency) {
    const interval = intervalMap[frequency];
    return Array.from({length: Math.ceil((endTime - startTime + 1) / interval)}, (_, i) =>
        [startTime + i * interval, Math.min(endTime, startTime + (i + 1) * interval - 1)]
    );
}
trincot
  • 317,000
  • 35
  • 244
  • 286