constructFrom.cjs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. exports.constructFrom = constructFrom;
  3. var _index = require("./constants.cjs");
  4. /**
  5. * @name constructFrom
  6. * @category Generic Helpers
  7. * @summary Constructs a date using the reference date and the value
  8. *
  9. * @description
  10. * The function constructs a new date using the constructor from the reference
  11. * date and the given value. It helps to build generic functions that accept
  12. * date extensions.
  13. *
  14. * It defaults to `Date` if the passed reference date is a number or a string.
  15. *
  16. * Starting from v3.7.0, it allows to construct a date using `[Symbol.for("constructDateFrom")]`
  17. * enabling to transfer extra properties from the reference date to the new date.
  18. * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)
  19. * that accept a time zone as a constructor argument.
  20. *
  21. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  22. *
  23. * @param date - The reference date to take constructor from
  24. * @param value - The value to create the date
  25. *
  26. * @returns Date initialized using the given date and value
  27. *
  28. * @example
  29. * import { constructFrom } from "date-fns";
  30. *
  31. * // A function that clones a date preserving the original type
  32. * function cloneDate<DateType extends Date>(date: DateType): DateType {
  33. * return constructFrom(
  34. * date, // Use constructor from the given date
  35. * date.getTime() // Use the date value to create a new date
  36. * );
  37. * }
  38. */
  39. function constructFrom(date, value) {
  40. if (typeof date === "function") return date(value);
  41. if (date && typeof date === "object" && _index.constructFromSymbol in date)
  42. return date[_index.constructFromSymbol](value);
  43. if (date instanceof Date) return new date.constructor(value);
  44. return new Date(value);
  45. }