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

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Ario Setiawan
  • 23
  • 2
  • 6
  • 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`? – Rajesh Sep 24 '20 at 07:04

1 Answers1

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));
Nick
  • 138,499
  • 22
  • 57
  • 95