Created
March 28, 2023 00:17
-
-
Save HallexCosta/a9a342b610cc9967df0a88bd04af6042 to your computer and use it in GitHub Desktop.
Calculate Hourly Rate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isTimeFormatValid(timeString) { | |
const timeRegex = /^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/; | |
const dateTimeRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/; | |
return timeRegex.test(timeString) || dateTimeRegex.test(timeString); | |
} | |
function calculateHourlyRate({ startTime, endTime, pricePerHour }) { | |
// Check if start time and end time are in a valid format | |
if (!isTimeFormatValid(startTime) || !isTimeFormatValid(endTime)) { | |
throw new Error('Invalid time format') | |
} | |
// Convert times to Date objects | |
const start = new Date(`01/01/2000 ${startTime}`); | |
const end = new Date(`01/01/2000 ${endTime}`); | |
// Check if start time is greater than end time | |
if (start.getTime() > end.getTime()) { | |
return 0; | |
} | |
// Calculate time difference in milliseconds | |
const timeDiff = end.getTime() - start.getTime(); | |
// Convert time difference to hours and minutes | |
const hoursWorked = Math.floor(timeDiff / (1000 * 60 * 60)); | |
const minutesWorked = Math.floor((timeDiff / (1000 * 60)) % 60); | |
// Calculate total value based on hourly rate | |
const totalValue = (hoursWorked + (minutesWorked / 60)) * pricePerHour; | |
return Math.ceil(totalValue); | |
} | |
console.log(calculateHourlyRate({ startTime: '00:01', endTime: '01:30', pricePerHour: 10 })); // Output: 15 | |
console.log(calculateHourlyRate({ startTime: '02:00', endTime: '01:00', pricePerHour: 10 })); // Output: 0 | |
console.log(calculateHourlyRate({ startTime: '2022-04-01 09:30:00', endTime: '2022-04-01 18:00:00', pricePerHour: 20 })); // Output: 180 | |
console.log(calculateHourlyRate({ startTime: '2022-04-01 09:30', endTime: '2022-04-01 18:00', pricePerHour: 20 })); // Output: 180 | |
console.log(calculateHourlyRate({ startTime: '09:30', endTime: '18:00', pricePerHour: 20 })); // Output: 180 | |
console.log(calculateHourlyRate({ startTime: 'invalid time format', endTime: '18:00', pricePerHour: 20 })); // Output: 'Invalid time format' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment