* 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>
67 lines
1.5 KiB
TypeScript
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;
|
|
};
|