【问题标题】:Get matching interval获取匹配区间
【发布时间】:2019-02-20 17:48:09
【问题描述】:

所以我从两个简单的事情开始:

  • 时间间隔列表及其匹配的间隔名称。
  • 还有一个 currentTime,例如("08:58"、"15:23"、"02:03")。

let intervals = {
    "08:00 - 09:00" : "Morning yoga",
    "09:00 - 10:00" : "Breakfast",
    "10:00 - 13:00" : "School Period",
    "13:00 - 14:00" : "Basketball",
    "14:00 - 16:00" : "Free Period",
    "16:00 - 17:00" : "Evening Meal",
    "17:00 - 18:00" : "Exercise Period",
    "18:00 - 19:00" : "Shower Block",
    "19:00 - 22:00" : "Evening Free Time",
    "22:00 - 23:00" : "Evening Rollcall",
    "23:00 - 08:00" : "Lights Out"
  }

我想将 interval 的名称 提取到给定的 currentTime 中,以便例如从:

  • "08:58" 结果:"Morning yoga"
  • "15:23" 结果:"Free Period"
  • "02:03" 结果:"Lights Out"

到目前为止我得到的是下面的代码,但显然里面有一些错误。

let getSchedule = function(time) {
  let scheduleIndex = 0;
  let current = getMinute(time);
  let intervalArray = []

  for (let key in schedule)
    intervalArray.push([getMinute(key.split(" - ")[0]),
      getMinute(key.split(" - ")[1])
    ]);

  for (let index = 0; index < intervalArray.length; index++) {
    let interval = intervalArray[index]
    if (current >= interval[0] && current < interval[1]) {
      scheduleIndex = index;
      break;
    }
  };
  return schedule[Object.keys(schedule)[scheduleIndex]]
}

let getMinute = function(time) {
  let hour = parseInt(time.split(":")[0]),
    minute = parseInt(time.split(":")[1]);
  return minute + hour * 60;
}

let result = getSchedule("16:22")
console.log(result)

result = getSchedule("02:00")
console.log(result)
<script>
  let schedule = {
    "08:00 - 09:00": "Morning yoga",
    "09:00 - 10:00": "Breakfast",
    "10:00 - 13:00": "School Period",
    "13:00 - 14:00": "Basketball",
    "14:00 - 16:00": "Free Period",
    "16:00 - 17:00": "Evening Meal",
    "17:00 - 18:00": "Exercise Period",
    "18:00 - 19:00": "Shower Block",
    "19:00 - 22:00": "Evening Free Time",
    "22:00 - 23:00": "Evening Rollcall",
    "23:00 - 08:00": "Lights Out"
  }
</script>

编辑:请注意,完整的时间会改变状态,以便 23:00 具有状态 Lights Out 而 22:59状态为Evening Rollcall。

还请注意,我无法更改 intervals 对象。它的结构必须保留。

【问题讨论】:

  • 你说显然有一些错误 - 请添加错误的详细信息,谢谢。
  • 那么如果时间是例如你期望什么? 23:00 ?
  • @CrayonViolent:整个小时将更改状态,以便 23:00 具有状态 Lights Out 而 22:59 具有状态Evening Rollcall.
  • 您的intervals 格式/结构是否需要这样?因为还有许多其他方式可以构建它,以使编码你想做的事情变得更加容易/优雅..
  • 问题中不包含实际的问题陈述。从表面上看,这个问题似乎是“为什么这个参数返回了错误的值?”,但实际上更像是“我如何重新组织我的代码,以便我可以编写许多函数”在任意调度数组中准确找到数组元素"

标签: javascript jquery time intervals


【解决方案1】:

脚本最初将scheduleIndex 设置为0(默认值),并且从不检查是否找到匹配间隔

您的逻辑永远不会匹配“熄灯”间隔,因为结束值小于开始值,而您的逻辑不允许这样做。

getSchedule 因此从schedule 返回“默认”元素,“Morning Yoga”而不是“Lights Out”。

可能的解决方案:

  1. 更改您的逻辑以正确匹配“熄灯”间隔。
  2. 将“熄灯”时间间隔分成“00:00 - 08:00”和“23:00 - 23:59”两部分并保持当前逻辑
  3. 保留您的逻辑并添加错误检查(将scheduleIndex 设置为无效值并在返回结果之前对其进行测试)并从计划中删除“熄灯”间隔,并假设任何不匹配的都是此默认间隔。 (如下所示)

let getSchedule = function(time) {
  let scheduleIndex = -1;
  let current = getMinute(time);
  let intervalArray = []

  for (let key in schedule)
    intervalArray.push([getMinute(key.split(" - ")[0]),
      getMinute(key.split(" - ")[1])
    ]);

  for (let index = 0; index < intervalArray.length; index++) {
    let interval = intervalArray[index]
    if (current >= interval[0] && current < interval[1]) {
      scheduleIndex = index;
      break;
    }
  };
  return -1 == scheduleIndex? "Lights Out" : schedule[Object.keys(schedule)[scheduleIndex]];
}

let getMinute = function(time) {
  let hour = parseInt(time.split(":")[0]),
    minute = parseInt(time.split(":")[1]);
  return minute + hour * 60;
}

let result = getSchedule("16:22")
console.log(result)

result = getSchedule("02:00")
console.log(result)
<script>
  let schedule = {
    "08:00 - 09:00": "Morning yoga",
    "09:00 - 10:00": "Breakfast",
    "10:00 - 13:00": "School Period",
    "13:00 - 14:00": "Basketball",
    "14:00 - 16:00": "Free Period",
    "16:00 - 17:00": "Evening Meal",
    "17:00 - 18:00": "Exercise Period",
    "18:00 - 19:00": "Shower Block",
    "19:00 - 22:00": "Evening Free Time",
    "22:00 - 23:00": "Evening Rollcall",
  }
</script>

【讨论】:

  • 我不想否认你的回答是正确的。我什至不认为这有多糟糕。不幸的是,例如,我使用这一行return -1 == scheduleIndex? ... 不像以前那样可变。我想找到一种可以执行不同schedule 方法的方法。你的方法对我来说相当不方便。而且由于我想以这种方式保留我的变量结构,因此您的回答更像是一种解决方法。还是谢谢你。
  • 不确定您的评论是什么意思,抱歉。你的意思是说你被那条线弄糊涂了? “不同的schedule 方法到底是什么意思?无论哪种方式,如果你想要的不仅仅是解决你的直接问题,你应该把它放在问题中
  • 不,我绝对不会感到困惑。问题是在 getSchedule 调用中添加 "Lights Out" 作为状态是一种解决方法。因为这使得该方法无法用于“熄灯”状态可能具有不同名称/位置的不同棚屋。
  • 对,但问题中没有提到该要求。你正在移动球门柱。话虽如此,通用技术是适用的。 “如果找不到匹配项,则返回默认值”。通常在这种情况下,默认值被传递给函数。您应该使用的部分是“测试是否找到匹配项”,这是您问题的根本原因
  • 您接受的解决方案并没有解决计划稀疏的问题。去掉“空闲时间”间隔,试试getSchedule("15:00")
【解决方案2】:

如果你改变数据结构,它会变得简单得多。

const schedule = {
  "Morning yoga": [800, 900],
  "Breakfast": [900, 1000]
};

const getSchedule = timeString => {
  const time = +timeString.replace(":", "");
  const result = [];
  for (const key in schedule) {
    if (time >= schedule[key][0] && time <= schedule[key][1]) {
      result.push(key);
    }
  }
  return result;
};

const result = getSchedule("09:22");
console.log(result);

【讨论】:

  • 虽然有帮助,但实际上并不能回答问题。
  • 我看到的问题是代码过于复杂。调试 OP 代码并不能解决这个问题。
【解决方案3】:

我的做法有点不同。可能对你有帮助。

let schedule = {
  "08:00 - 09:00": "Morning yoga",
  "09:00 - 10:00": "Breakfast",
  "10:00 - 13:00": "School Period",
  "13:00 - 14:00": "Basketball",
  "14:00 - 16:00": "Free Period",
  "16:00 - 17:00": "Evening Meal",
  "17:00 - 18:00": "Exercise Period",
  "18:00 - 19:00": "Shower Block",
  "19:00 - 22:00": "Evening Free Time",
  "22:00 - 23:00": "Evening Rollcall",
  "23:00 - 08:00": "Lights Out"
}
var getSchedule = function(time) {
let fullDaySchedule = {}
  Object.entries(schedule).forEach(([currentTime, work]) => {
    let startTime = +currentTime.split(" - ")[0].split(":")[0],
      endTime = +currentTime.split(" - ")[1].split(":")[0];

    (startTime > endTime) && (endTime = (23 - startTime) + (23 + endTime))

    for (let index = startTime; index <= endTime; index++) {
      fullDaySchedule[(index % 24)] = work;
    }
  })

  console.log(fullDaySchedule[+time.split(":")[0]])
}

// You can test this
getSchedule("02:00")

【讨论】:

  • 我看到你建议在顶部添加“let schedule”。没关系。您现在可以对此进行测试,如果这有帮助,请告诉我。
  • 嘿 Nitish Narang,@Tibrogargan 是对的。将let schedule = { "08:00 - 09:00": "Morning yoga", "09:00 - 10:00": "Breakfast", "10:00 - 13:00": "School Period", "13:00 - 14:00": "Basketball", "16:00 - 17:00": "Evening Meal", "17:00 - 18:00": "Exercise Period", "18:00 - 19:00": "Shower Block", "19:00 - 22:00": "Evening Free Time", "22:00 - 23:00": "Evening Rollcall", "23:00 - 08:00": "Lights Out" }; 与getSchedule("15:00") 结合使用无效。
  • 抱歉,没听懂。对于您所指的时间表对象,没有时间数据 - “15:00”,但它在您发布的问题中。
  • 我认为它丢失了 - "14:00 - 16:00": "Free Period" 在日程对象中。
  • "你接受的方案并没有解决sparse schedule的问题。去掉"14:00 - 16:00":"Free Period"区间,试试getSchedule("15:00") "。
【解决方案4】:

我已经重构了您的代码a bit。它以更实用的方式完成,我相信可读的方式。我还考虑了一些边缘情况(当然不是全部,因为我相信情况并非如此)。看看这个坏男孩:

// Keep in mind that for e.g. `14:00` you have two parameters that fullfil the requirement: 
// `Basketball` and `Free Period`. 
// This constrain should be specified in the code somewhere.
// Otherwise the first value will be taken.
let schedule = {
    "08:00 - 09:00" : "Morning yoga",
    "09:00 - 10:00" : "Breakfast",
    "10:00 - 13:00" : "School Period",
    "13:00 - 14:00" : "Basketball",
    "14:00 - 16:00" : "Free Period",
    "16:00 - 17:00" : "Evening Meal",
    "17:00 - 18:00" : "Exercise Period",
    "18:00 - 19:00" : "Shower Block",
    "19:00 - 22:00" : "Evening Free Time",
    "22:00 - 23:00" : "Evening Rollcall",
    "23:00 - 08:00" : "Lights Out"
  }


let newSchedule = Object
  .entries(schedule)
  .reduce((acc, entry) => {
    const newInterval = {
      from: Number(entry[0].slice(0,5).replace(':','')),
      to: Number(entry[0].slice(-5).replace(':','')),
      value: entry[1],
    };
    return [...acc, newInterval];
  }, [])
  .reduce((acc, { from, to, value}) => {
    // this step is only needed when you can't set ranges in `schedule` object manually
    let intervals = [{ from, to, value }];
    if(from > to) {
      intervals = [
        { 
          from, 
          to: 2400,
          value,
        },
        { 
          from: 0, 
          to,
          value,
        },
      ];
    }
    return [...acc, ...intervals];
  }, []);

const getSchedule = (time) => {
  const timeAsNumber = Number(time.replace(':', ''));
  return newSchedule.find(interval => {
    return timeAsNumber >= interval.from && timeAsNumber <= interval.to;
  }).value
}

console.log(getSchedule('02:00'))
console.log(getSchedule('18:00'))

我鼓励您进一步重构它,例如进入更多功能的方法,更高的性能,或者只是更清洁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多