M
M
magary42020-06-03 23:46:59
JavaScript
magary4, 2020-06-03 23:46:59

How to subtract arrays in functional style?

records of the form arrive from the database

[
{type: "open", from: "2020-08-11 10:00", to: "2020-08-11 17:00"},
{type: "closed", from: "2020-08-11 12:00", to: "2020-08-11 13:00"},
{type: "closed", from: "2020-08-11 15:00", to: "2020-08-11 16:00"}
]


how to assemble an array of the form ["10:00", "10:30", "11:00", "11:30", "13:00", "13:30", "14:00", " 14:30", "16:00", "16:30"]

in functional style

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-06-04
@magary4

function getIntervals (arr) {
   const mlsInterval = 30 * 60 * 1000

   const openHours = arr.filter(v => v.type === 'open').flatMap(v => {
      const [d1, d2] = [new Date(v.from).getTime(), new Date(v.to).getTime()]
      const length = Math.floor(( d2 - d1 ) / mlsInterval)
      const hours = Array.from({ length }, (z, ind) => new Date(d1 + ind * mlsInterval))
      return hours
   })

   const closeIntervals = arr.filter(v => v.type === 'closed').map(v => 
     [new Date(v.from).getTime(), new Date(v.to).getTime()]       
   )

   const result = openHours.filter(v =>  
     !closeIntervals.some(([start, stop]) => start <= v && stop > v)
   ).map(v => new Date(v).toString().match(/\d\d:\d\d:\d\d/g)[0])

   return result
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question