UNPKG

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