UNPKG

1.87 kBJavaScriptView Raw
1import { normalizeDates } from "./_lib/normalizeDates.js";
2import { max } from "./max.js";
3import { min } from "./min.js";
4
5/**
6 * The {@link clamp} function options.
7 */
8
9/**
10 * The {@link clamp} function result type. It resolves the proper data type.
11 * It uses the first argument date object type, starting from the date argument,
12 * then the start interval date, and finally the end interval date. If
13 * a context function is passed, it uses the context function return type.
14 */
15
16/**
17 * @name clamp
18 * @category Interval Helpers
19 * @summary Return a date bounded by the start and the end of the given interval.
20 *
21 * @description
22 * Clamps a date to the lower bound with the start of the interval and the upper
23 * bound with the end of the interval.
24 *
25 * - When the date is less than the start of the interval, the start is returned.
26 * - When the date is greater than the end of the interval, the end is returned.
27 * - Otherwise the date is returned.
28 *
29 * @typeParam DateType - Date argument type.
30 * @typeParam IntervalType - Interval argument type.
31 * @typeParam Options - Options type.
32 *
33 * @param date - The date to be bounded
34 * @param interval - The interval to bound to
35 * @param options - An object with options
36 *
37 * @returns The date bounded by the start and the end of the interval
38 *
39 * @example
40 * // What is Mar 21, 2021 bounded to an interval starting at Mar 22, 2021 and ending at Apr 01, 2021
41 * const result = clamp(new Date(2021, 2, 21), {
42 * start: new Date(2021, 2, 22),
43 * end: new Date(2021, 3, 1),
44 * })
45 * //=> Mon Mar 22 2021 00:00:00
46 */
47export function clamp(date, interval, options) {
48 const [date_, start, end] = normalizeDates(
49 options?.in,
50 date,
51 interval.start,
52 interval.end,
53 );
54
55 return min([max([date_, start], options), end], options);
56}
57
58// Fallback for modularized imports:
59export default clamp;