constructFrom.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. exports.constructFrom = constructFrom;
  3. /**
  4. * @name constructFrom
  5. * @category Generic Helpers
  6. * @summary Constructs a date using the reference date and the value
  7. *
  8. * @description
  9. * The function constructs a new date using the constructor from the reference
  10. * date and the given value. It helps to build generic functions that accept
  11. * date extensions.
  12. *
  13. * It defaults to `Date` if the passed reference date is a number or a string.
  14. *
  15. * @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).
  16. *
  17. * @param date - The reference date to take constructor from
  18. * @param value - The value to create the date
  19. *
  20. * @returns Date initialized using the given date and value
  21. *
  22. * @example
  23. * import { constructFrom } from 'date-fns'
  24. *
  25. * // A function that clones a date preserving the original type
  26. * function cloneDate<DateType extends Date(date: DateType): DateType {
  27. * return constructFrom(
  28. * date, // Use contrustor from the given date
  29. * date.getTime() // Use the date value to create a new date
  30. * )
  31. * }
  32. */
  33. function constructFrom(date, value) {
  34. if (date instanceof Date) {
  35. return new date.constructor(value);
  36. } else {
  37. return new Date(value);
  38. }
  39. }