Files
openstapps/packages/core/src/things/abstract/range.ts

89 lines
2.0 KiB
TypeScript

/*
* Copyright (C) 2021-2022 Open StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {SCISO8601Date} from '../../general/time.js';
/**
* Date Range
*/
export type SCISO8601DateRange = SCRange<SCISO8601Date>;
/**
* Checks if a value is inside a range
* @param value the value to check
* @param range the range
*/
export function isInRange<T>(value: T, range: SCRange<T>): boolean {
return (
(range.lt == undefined ? (range.lte == undefined ? true : range.lte >= value) : range.lt > value) &&
(range.gt == undefined ? (range.gte == undefined ? true : range.gte <= value) : range.gt < value)
);
}
/**
* Format a range
* @example '0..4'
* @example '1=..=3'
* @example '0..=3'
*/
export function formatRange<T>(range: SCRange<T>): string {
return `${range.gt ?? range.gte}${range.gte == undefined ? '' : '='}..${range.lte == undefined ? '' : '='}${
range.lt ?? range.lte
}`;
}
/**
* Generic range type
*/
export type SCRange<T> =
| {
/**
* Greater than value
*/
gt?: never;
/**
* Greater or equal to value
*/
gte?: T;
/**
* Greater than value
*/
lt?: never;
/**
* Greater or equal to value
*/
lte?: T;
}
| {
gt?: T;
gte?: never;
lt?: T;
lte?: never;
}
| {
gt?: T;
gte?: never;
lt?: never;
lte?: T;
}
| {
gt?: never;
gte?: T;
lt?: T;
lte?: never;
};