Remove duplicate code for parsing numbers.

This commit is contained in:
baldo 2022-09-20 19:11:36 +02:00
commit 511f7c4f80
9 changed files with 183 additions and 108 deletions

View file

@ -4,7 +4,7 @@ import { onMounted, ref, watch } from "vue";
import { useConfigStore } from "@/stores/config";
import type { Coordinates } from "@/types";
import * as L from "leaflet";
import { parseToFloat } from "@/utils/Numbers";
import { parseToFloat } from "@/shared/utils/numbers";
import type { LatLngTuple } from "leaflet";
import { forConstraint } from "@/shared/validation/validator";
import CONSTRAINTS from "@/shared/validation/constraints";

View file

@ -32,7 +32,7 @@ import OutsideOfCommunityConfirmationForm from "@/components/nodes/OutsideOfComm
import CheckboxInput from "@/components/form/CheckboxInput.vue";
import InfoCard from "@/components/InfoCard.vue";
import { isPointInPolygon } from "geolib";
import { parseToFloat } from "@/utils/Numbers";
import { parseToFloat } from "@/shared/utils/numbers";
import { forConstraint } from "../../shared/validation/validator";
const configStore = useConfigStore();

View file

@ -1,71 +0,0 @@
import { isNumber } from "@/shared/types";
// TODO: Write tests!
export function isInteger(arg: unknown): arg is number {
return isNumber(arg) && Number.isInteger(arg);
}
export function parseToInteger(arg: unknown, radix: number): number {
if (isInteger(arg)) {
return arg;
}
switch (typeof arg) {
case "number":
throw new Error(`Not an integer: ${arg}`);
case "string": {
if (radix < 2 || radix > 36 || isNaN(radix)) {
throw new Error(`Radix out of range: ${radix}`);
}
const str = (arg as string).trim();
const num = parseInt(str, radix);
if (isNaN(num)) {
throw new Error(`Not a valid number (radix: ${radix}): ${str}`);
}
if (num.toString(radix).toLowerCase() !== str.toLowerCase()) {
throw new Error(
`Parsed integer does not match given string (radix: ${radix}): ${str}`
);
}
return num;
}
default:
throw new Error(`Cannot parse number (radix: ${radix}): ${arg}`);
}
}
export function isFloat(arg: unknown): arg is number {
return isNumber(arg) && Number.isFinite(arg);
}
export function parseToFloat(arg: unknown): number {
if (isFloat(arg)) {
return arg;
}
switch (typeof arg) {
case "number":
throw new Error(`Not a finite number: ${arg}`);
case "string": {
let str = (arg as string).trim();
const num = parseFloat(str);
if (isNaN(num)) {
throw new Error(`Not a valid number: ${str}`);
}
if (Number.isInteger(num)) {
str = str.replace(/\.0+$/, "");
}
if (num.toString(10) !== str) {
throw new Error(
`Parsed float does not match given string: ${num.toString(
10
)} !== ${str}`
);
}
return num;
}
default:
throw new Error(`Cannot parse number: ${arg}`);
}
}