检查某个时间范围是否不在其他时间范围内?

时间:2019-05-28 14:48:54

标签: javascript

我需要检查给定的时间范围是否可用。

繁忙时间的阵列:

[
  { from: 2, to: 4 },
  { from: 8, to: 10 }
]

我要检查的车厢

{ from: 3, to: 6 }

预期结果:

{ from: 1, to: 2 } // true
{ from: 5, to: 7 } // true
{ from: 3, to: 4 } // false
{ from: 9, to: 10 } // false

1 个答案:

答案 0 :(得分:4)

您可以使用some()

const arr = [
  { from: 2, to: 4 },
  { from: 8, to: 10 }
]

function checkTime(arr,obj){
  return !arr.some(x => x.from <= obj.from && x.to >= obj.to);
}

let tests = [
  { from: 1, to: 2 },
  { from: 5, to: 7 }, 
  { from: 3, to: 4 },
  { from: 9, to: 10 }
]
tests.forEach(x => console.log(checkTime(arr,x)));