I’ve been battling ChatGPT for hours now and can’t get satisfied with this simple algorithm in TypeScript.
function computeUpcomingNotificationTimestamp(
currentTimestamp: number = Date.now(),
day: number = 1,
hours: number = 10,
minutes: number = 1
): number {
const currentTimeInMilliseconds: number =
date.getHours() * 60 * 60 * 1000 // Hours to milliseconds
+date.getMinutes() * 60 * 1000 // Minutes to milliseconds
+date.getSeconds() * 1000 // Seconds to milliseconds
+date.getMilliseconds(); // Milliseconds
const timeOfNotification: number =
hours * 60 * 60 * 1000 // Hours to milliseconds
+minutes * 60 * 1000; // Minutes to milliseconds
if (date.getDay() === day) {
if (currentTimeInMilliseconds >= timeOfNotification) {
date.setDate(date.getDate() + 7);
}
} else {
while (date.getDay() !== day) {
date.setDate(date.getDate() + 1);
}
}
date.setHours(hours, minutes, 0, 0);
return date.getTime();
}
This solution is (hopefully) correct and moves timestamp to the nearest Monday 10:01 AM. What I wish to achieve is a solution that has these properties.
Comprehensible for humans
- it must be readily apparent, so transparent a CHILD should grasp it instantly and SWEAR it is correct. If it were a suspect domicile and you were a cop who have 10 seconds to persuade the judge to grant you a search warrant, you MUST be able to SWAY HIM!
- No hacks, no bit-shifts, no Quake 3 arena stuff, nothing too clever
- just something concisely elegant and vivid
Other important features
- correct
- good programming practises (no spaghetti code, complicated conditions, nested if-else)
- functional, if it serves the purpose
- pragmatic (if there is a library, just use it please)
This is the closest I got, but there must be a better way. I would be beholden to you, the community.
Update
The original solution wasn’t even correct! Here is the correct one. Can you make it shorter?
2
Answers
You could try this.