Answer the question
In order to leave comments, you need to log in
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"}
]
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question