Files
twenty/front/src/utils/cast-as-positive-integer-or-null.ts
gitstart-twenty 5acafe2fc6 Chore(front): Add more typeguards (#2136)
* Chore(front): Add more typeguards

Co-authored-by: Benjamin Mayanja V <vibenjamin6@gmail.com>
Co-authored-by: KlingerMatheus <klinger.matheus@gitstart.dev>

* Remove source map generation to avoid warnings

---------

Co-authored-by: Benjamin Mayanja V <vibenjamin6@gmail.com>
Co-authored-by: KlingerMatheus <klinger.matheus@gitstart.dev>
Co-authored-by: Charles Bochet <charles@twenty.com>
2023-10-24 09:26:47 +02:00

67 lines
1.5 KiB
TypeScript

import { isInteger, isNull, isNumber, isString } from '@sniptt/guards';
export const canBeCastAsPositiveIntegerOrNull = (
probablePositiveNumberOrNull: string | undefined | number | null,
): probablePositiveNumberOrNull is number | null => {
if (probablePositiveNumberOrNull === undefined) {
return false;
}
if (isNumber(probablePositiveNumberOrNull)) {
return (
Number.isInteger(probablePositiveNumberOrNull) &&
Math.sign(probablePositiveNumberOrNull) !== -1
);
}
if (isNull(probablePositiveNumberOrNull)) {
return true;
}
if (probablePositiveNumberOrNull === '') {
return true;
}
if (isString(probablePositiveNumberOrNull)) {
const stringAsNumber = +probablePositiveNumberOrNull;
if (isNaN(stringAsNumber)) {
return false;
}
if (isInteger(stringAsNumber) && Math.sign(stringAsNumber) !== -1) {
return true;
}
}
return false;
};
export const castAsPositiveIntegerOrNull = (
probablePositiveNumberOrNull: string | undefined | number | null,
): number | null => {
if (
canBeCastAsPositiveIntegerOrNull(probablePositiveNumberOrNull) === false
) {
throw new Error('Cannot cast to positive number or null');
}
if (probablePositiveNumberOrNull === null) {
return null;
}
if (probablePositiveNumberOrNull === '') {
return null;
}
if (isNumber(probablePositiveNumberOrNull)) {
return probablePositiveNumberOrNull;
}
if (isString(probablePositiveNumberOrNull)) {
return +probablePositiveNumberOrNull;
}
return null;
};