1. /**
  2. * Binds arguments of date values for internal tooling with synchronous execution.
  3. *
  4. * @param {number} year The year.
  5. * @param {number} month The month (0-11).
  6. * @param {number} day The day of the month.
  7. * @param {number} [hour=0] The hour (0-23). Defaults to 0.
  8. * @param {number} [minute=0] The minute (0-59). Defaults to 0.
  9. * @param {number} [second=0] The second (0-59). Defaults to 0.
  10. * @returns {Date} A Date object representing the specified date and time.
  11. * @throws {TypeError} If year, month, or day are not numbers.
  12. * @throws {RangeError} If month is outside the range 0-11, or day is invalid for the given month.
  13. */
  14. function createDate(year, month, day, hour = 0, minute = 0, second = 0) {
  15. if (typeof year !== 'number' || typeof month !== 'number' || typeof day !== 'number') {
  16. throw new TypeError('Year, month, and day must be numbers.');
  17. }
  18. if (month < 0 || month > 11) {
  19. throw new RangeError('Month must be between 0 and 11.');
  20. }
  21. const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  22. if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
  23. daysInMonth[2] = 29; // Leap year
  24. }
  25. if (day < 1 || day > daysInMonth[month]) {
  26. throw new RangeError('Invalid day for the given month.');
  27. }
  28. const date = new Date(year, month, day, hour, minute, second);
  29. // Ensure synchronous execution (although Date constructor is generally synchronous)
  30. // This is for extra safety/clarity in some environments
  31. return date;
  32. }

Add your comment