1

I need to check if the given time range is available or not.

Array with busy hours:

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

The compartment I want to check

{ from: 3, to: 6 }

Expected result:

{ from: 1, to: 2 } // true
{ from: 5, to: 7 } // true
{ from: 3, to: 4 } // false
{ from: 9, to: 10 } // false
2
  • 1
    I imagine you could start with a for loop of some kind. What have you tried? Please show your best attempt and explain what went wrong (errors, unexpected results, etc.)
    – p.s.w.g
    Commented May 28, 2019 at 14:51
  • What exactly do you want to find out ? whether it lies in any one range from 1st array ? Commented May 28, 2019 at 14:52

1 Answer 1

3

You can use 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)));

4
  • I am sorry, I should add some examples to the question. Thank you for recommending Array.some() function, now I have to remember previous results ;)
    – Adee
    Commented May 28, 2019 at 15:07
  • @Adee You might explain the question a little more please what is role of { from: 3, to: 6 }. Explain why particular input returns true or false.
    – Maheer Ali
    Commented May 28, 2019 at 15:13
  • I assume that the day is 24 hours (from 0 - 23). I need to check if the given time range is free (there are no other reservations at this time).
    – Adee
    Commented May 28, 2019 at 15:18
  • It is much better, but some options still disagree {from: 1, to: 3}, {from: 5, to: 10}... What do you think about changing the compartments into array elements? Example {from: 2, to: 5} => [2,3,4,5] or without borders [3,4]?
    – Adee
    Commented May 28, 2019 at 15:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.