Which algorithm should you choose?

  • 0
    There are time intervals in text format (for example, on Friday from 3 to 4 Petya is busy, and from 6 to 8 Alyosha) and you need to find the time at which both Petya and Alyosha will be free.
    I simplified it a lot, but the point is
    Time data from how long to how long is unknown, should work on any.
    Question:
    Maybe there are some libraries for working with time intervals? Or ideas how to make it simple? Algorithm of some kind.
    I rewrite it for the third time and I get huge canvases of code for 2-3 thousand lines in which I myself get confused T_T
    JavaScript Anonymous, Apr 12, 2019

  • 1 Answers
  • 0
    const data = [
    "Пн 02:15 - Пн 07:40",
    "Пн 04:20 - Пн 06:00",
    "Пн 06:30 - Пн 09:15",
    "Пн 09:50 - Пн 15:00",
    "Пн 17:00 - Вт 23:20"];

    const weekDays = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"]

    const periods = data
    .map(v =>
    v
    .split(" - ")
    .map(v =>
    String(weekDays.indexOf(v.substring(0, 2))) +
    v.substring(2)
    )
    )
    .sort((a, b) => {
    if (a[0] < b[0]) return -1
    if (a[0] > b[0]) return 1
    return 0
    })
    .concat([["6 23:59", ""]])

    const freePeriods = periods.reduce((agg, period) => {
    if (period[0] > agg.lastOccupied) agg.freePeriods.push([agg.lastOccupied, period[0]])
    if (agg.lastOccupied < period[1]) agg.lastOccupied = period[1]
    return agg
    }, { freePeriods: [], lastOccupied: "0 00:00"} )
    .freePeriods
    .map(v =>
    v.map(v => weekDays[v[0]] + v.substring(1)).join(" - ")
    )

    console.log(freePeriods) // ["Пн 00:00 - Пн 02:15", "Пн 09:15 - Пн 09:50", "Пн 15:00 - Пн 17:00", "Вт 23:20 - Вс 23:59"]
    Bennett Thomas

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!