datetime.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const benchmark_1 = __importDefault(require("benchmark"));
  7. const datetimeValidationSuite = new benchmark_1.default.Suite("datetime");
  8. const DATA = "2021-01-01";
  9. const MONTHS_31 = new Set([1, 3, 5, 7, 8, 10, 12]);
  10. const MONTHS_30 = new Set([4, 6, 9, 11]);
  11. const simpleDatetimeRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
  12. 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))$/;
  13. 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])))$/;
  14. datetimeValidationSuite
  15. .add("new Date()", () => {
  16. return !Number.isNaN(new Date(DATA).getTime());
  17. })
  18. .add("regex (no validation)", () => {
  19. return simpleDatetimeRegex.test(DATA);
  20. })
  21. .add("regex (no leap year)", () => {
  22. return datetimeRegexNoLeapYearValidation.test(DATA);
  23. })
  24. .add("regex (w/ leap year)", () => {
  25. return datetimeRegexWithLeapYearValidation.test(DATA);
  26. })
  27. .add("capture groups + code", () => {
  28. const match = DATA.match(simpleDatetimeRegex);
  29. if (!match)
  30. return false;
  31. // Extract year, month, and day from the capture groups
  32. const year = Number.parseInt(match[1], 10);
  33. const month = Number.parseInt(match[2], 10); // month is 0-indexed in JavaScript Date, so subtract 1
  34. const day = Number.parseInt(match[3], 10);
  35. if (month === 2) {
  36. if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
  37. return day <= 29;
  38. }
  39. return day <= 28;
  40. }
  41. if (MONTHS_30.has(month)) {
  42. return day <= 30;
  43. }
  44. if (MONTHS_31.has(month)) {
  45. return day <= 31;
  46. }
  47. return false;
  48. })
  49. .on("cycle", (e) => {
  50. console.log(`${datetimeValidationSuite.name}: ${e.target}`);
  51. });
  52. exports.default = {
  53. suites: [datetimeValidationSuite],
  54. };