constructFrom.js 1.8 KB

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