UNPKG

@terminus/ngx-tools

Version:

[![CircleCI][circle-badge]][circle-link] [![codecov][codecov-badge]][codecov-project] [![semantic-release][semantic-release-badge]][semantic-release] [![MIT License][license-image]][license-url] <br> [![NPM version][npm-version-image]][npm-url] [![Github

60 lines (54 loc) 1.97 kB
/** * Coerces a data-bound value (typically a string) to a boolean. * * @param value - The value to coerce to a boolean * @returns The boolean * * @example * coerceBooleanProperty('true'); // Returns: true */ // eslint-disable-next-line @typescript-eslint/no-explicit-any const coerceBooleanProperty = (value) => value != null && `${value}` !== 'false'; function coerceNumberProperty(value, fallbackValue = 0) { return isNumberValue(value) ? Number(value) : fallbackValue; } /** * Whether the provided value is considered a number. * * ParseFloat(value) handles most of the cases we're interested in (it treats null, empty string, * and other non-number values as NaN, where Number just uses 0) but it considers the string * '123hello' to be a valid number. Therefore we also check if Number(value) is NaN. * NOTE: TypeScript seems to consider `parseFloat(value)` unsafe. In my tests there are no values which `parseFloat` * cannot handle safely. * * @private * @param value */ const isNumberValue = (value) => !isNaN(parseFloat(value)) && !isNaN(Number(value)); function coerceDateProperty(value, fallbackValue = new Date()) { return isDateValue(value) ? new Date(value) : fallbackValue; } /** * Whether the provided value is considered a date. * * @private * @param value * @returns Boolean */ const isDateValue = (value) => !isNaN(Date.parse(value)); /** * Wraps the provided value in an array, unless the provided value is an array. * * @param value - The value to coerce to an array * @returns An array * * @example * coerceArray<string>('foo'); // Returns: ['foo'] * coerceArray(['foo']); // Returns: ['foo'] */ const coerceArray = (value) => (Array.isArray(value) ? value : [value]); /** * Generated bundle index. Do not edit. */ export { coerceArray, coerceBooleanProperty, coerceDateProperty, coerceNumberProperty, isDateValue, isNumberValue }; //# sourceMappingURL=terminus-ngx-tools-coercion.js.map