UNPKG

1.89 kBJavaScriptView Raw
1import { constructFromSymbol } from "./constants.js";
2
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 * Starting from v3.7.0, it allows to construct a date using `[Symbol.for("constructDateFrom")]`
16 * enabling to transfer extra properties from the reference date to the new date.
17 * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)
18 * that accept a time zone as a constructor argument.
19 *
20 * @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).
21 *
22 * @param date - The reference date to take constructor from
23 * @param value - The value to create the date
24 *
25 * @returns Date initialized using the given date and value
26 *
27 * @example
28 * import { constructFrom } from "./constructFrom/date-fns";
29 *
30 * // A function that clones a date preserving the original type
31 * function cloneDate<DateType extends Date>(date: DateType): DateType {
32 * return constructFrom(
33 * date, // Use constructor from the given date
34 * date.getTime() // Use the date value to create a new date
35 * );
36 * }
37 */
38export function constructFrom(date, value) {
39 if (typeof date === "function") return date(value);
40
41 if (date && typeof date === "object" && constructFromSymbol in date)
42 return date[constructFromSymbol](value);
43
44 if (date instanceof Date) return new date.constructor(value);
45
46 return new Date(value);
47}
48
49// Fallback for modularized imports:
50export default constructFrom;