Remove duplicate code for parsing numbers.
This commit is contained in:
parent
15d3f45bae
commit
b1075aa2ec
6 changed files with 181 additions and 35 deletions
server/shared/utils
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* Utility functions all around strings.
|
||||
*/
|
||||
import { isInteger, type MAC } from "../types";
|
||||
import type { MAC } from "../types";
|
||||
|
||||
/**
|
||||
* Trims the given `string` and replaces multiple whitespaces by one space each.
|
||||
|
@ -39,31 +39,3 @@ export function normalizeMac(mac: MAC): MAC {
|
|||
|
||||
return macParts.join(":") as MAC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the given `string` and converts it into an integer.
|
||||
*
|
||||
* For a `string` to be considered a valid representation of an integer `number` it has to satisfy the
|
||||
* following criteria:
|
||||
*
|
||||
* * The integer is base `10`.
|
||||
* * The `string` starts with an optional `+` or `-` sign followed by one or more digits.
|
||||
* * The first digit must not be `0`.
|
||||
* * The `string` does not contain any other characters.
|
||||
*
|
||||
* @param str - `string` to parse.
|
||||
* @returns The parsed integer `number`.
|
||||
* @throws {@link SyntaxError} - If the given `string` does not represent a valid integer.
|
||||
*/
|
||||
export function parseInteger(str: string): number {
|
||||
const parsed = parseInt(str, 10);
|
||||
const original = str.startsWith("+") ? str.slice(1) : str;
|
||||
|
||||
if (isInteger(parsed) && parsed.toString() === original) {
|
||||
return parsed;
|
||||
} else {
|
||||
throw new SyntaxError(
|
||||
`String does not represent a valid integer: "${str}"`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue