datetime.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import Benchmark from "benchmark";
  2. const datetimeValidationSuite = new Benchmark.Suite("datetime");
  3. const DATA = "2021-01-01";
  4. const MONTHS_31 = new Set([1, 3, 5, 7, 8, 10, 12]);
  5. const MONTHS_30 = new Set([4, 6, 9, 11]);
  6. const simpleDatetimeRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
  7. const datetimeRegexNoLeapYearValidation = /^\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d))$/;
  8. const datetimeRegexWithLeapYearValidation = /^((\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\d|3[01])|(0[469]|11)-(0[1-9]|[12]\d|30)|(02)-(0[1-9]|1\d|2[0-8])))$/;
  9. datetimeValidationSuite
  10. .add("new Date()", () => {
  11. return !Number.isNaN(new Date(DATA).getTime());
  12. })
  13. .add("regex (no validation)", () => {
  14. return simpleDatetimeRegex.test(DATA);
  15. })
  16. .add("regex (no leap year)", () => {
  17. return datetimeRegexNoLeapYearValidation.test(DATA);
  18. })
  19. .add("regex (w/ leap year)", () => {
  20. return datetimeRegexWithLeapYearValidation.test(DATA);
  21. })
  22. .add("capture groups + code", () => {
  23. const match = DATA.match(simpleDatetimeRegex);
  24. if (!match)
  25. return false;
  26. // Extract year, month, and day from the capture groups
  27. const year = Number.parseInt(match[1], 10);
  28. const month = Number.parseInt(match[2], 10); // month is 0-indexed in JavaScript Date, so subtract 1
  29. const day = Number.parseInt(match[3], 10);
  30. if (month === 2) {
  31. if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
  32. return day <= 29;
  33. }
  34. return day <= 28;
  35. }
  36. if (MONTHS_30.has(month)) {
  37. return day <= 30;
  38. }
  39. if (MONTHS_31.has(month)) {
  40. return day <= 31;
  41. }
  42. return false;
  43. })
  44. .on("cycle", (e) => {
  45. console.log(`${datetimeValidationSuite.name}: ${e.target}`);
  46. });
  47. export default {
  48. suites: [datetimeValidationSuite],
  49. };