0

I want to make shift parser helper which is generate time of work shift, below is shift rule

  let shift_rule = [
    {
      shift: '07-12',
      start: 7,
      finish: 12
    },
    {
      shift: '12-17',
      start: 12,
      finish: 17
    },
    {
      shift: '17-22',
      start: 17,
      finish: 22
    },
  ];

If time shift is timeStart = 7, timeFinish = 17

Expected output:

[
    {
      shift: '07-12',
      start: 7,
      finish: 12
    },
    {
      shift: '12-17'
      start: 12,
      finish: 17
    },
]

I'd already try to solve with this code

shift_rule
    .map((time) => ((timeFinish > time.start)) && time)
    .filter(item => typeof item !== 'boolean');

But when filter was time.start = 17 , timeFinish = 22, it show:

[
    {
      shift: '07-12',
      start: 7,
      finish: 12
    },
    {
      shift: '12-17',
      start: 12,
      finish: 17
    },
    {
      shift: '17-22',
      start: 17,
      finish: 22
    },
  ]

Hope can be solved with ES6 Functional

1
  • First, its always better and cleaner to use filter first and then use map. typeof item !== 'boolean' is kinda a bad check. Second, in your map function, you are not checking for timeStart with anything. Should it not be time.start >= timeStart && time.finish <= timeFinish? Commented Sep 24, 2020 at 7:04

1 Answer 1

2

You can check for overlapping time ranges by checking that the start of each range is before the end of the other (see for example this question). You can implement that code in a filter and then use map to return just the shift name:

let shift_rule = [
  { shift: '07-12', start: 7, finish: 12 },
  { shift: '12-17', start: 12, finish: 17 },
  { shift: '17-22', start: 17, finish: 22 } 
];

const filter_shifts = (rules, timeStart, timeFinish) =>
  rules.filter(s => s.start < timeFinish && s.finish > timeStart).map(s => s.shift);

console.log(filter_shifts(shift_rule, 7, 17));
console.log(filter_shifts(shift_rule, 17, 22));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.