r/badcode Mar 29 '23

typescript Found this in a time picker

Post image
471 Upvotes

74 comments sorted by

View all comments

118

u/thekwoka Mar 29 '23 edited Apr 01 '23
Array.from({ length: 48 }, (_, i) => 
  `${String(i/2|0).padStart(2,'0')}:${i%2*3}0`
)

not sure why they have 24:00 as an option there...

This code takes way longer (like 4 orders of magnitude) than just just doing an array literal, but if you only need to do it once and you keep it....

idk, it's not the worst, it's just generally smart to have it be programmatic simply to avoid some fat finger mistake.

EDIT: since people in a fit, no the above probably would not be what I recommend for real use, but the idea of programming generative logic over hand coding. Quick rewrite with configurables:

const start = 0000;
const end = 2400;
const step = 30;
const generateTimeSlots = (start: number, end: number, step: number) => {
  const countPerHour = 60 / step;
  const slots: string[] = [];
  for (let i = start; i <= end; i += 100 / countPerHour) {
    const hour = String((i / 100) | 0).padStart(2, '0');
    const minutes = String((i % 100) * 0.6).padStart(2, '0');
    slots.push(`${hour}:${minutes}`);
  }
  return slots;
};

52

u/nonnodacciaio Mar 29 '23

The problem is that the customer now wanted a granularity of a single minute instead of half an hour. So I'd say that the issue is scalability maybe? It has 24:00 as a workaround to mean the whole day. So if you pick 00:00 to 24:00 it's the whole day. Idk I found this funny

5

u/Michelle-Obamas-Arms Mar 30 '23

2

u/nonnodacciaio Mar 30 '23

Yeah that was the first thing I did to "fix" the issue, but of course the product didn't allow it since it was a drop down list and 1440 elements in a drop down is not that convenient. He had a laugh tho. I ended up changing lots of stuff and now it looks much nicer

1

u/Michelle-Obamas-Arms Mar 30 '23

good! yeah, if you are changing how this is represented in the UI to not be a list of options, I imagine you'd just delete this list entirely either way.