Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adapted number regex to allow scientific notation #490

Merged
merged 2 commits into from
Dec 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import {
ValuetypeVisitor,
} from '@jvalue/jayvee-language-server';

const DECIMAL_COMMA_SEPARATOR_REGEX = /^[+-]?([0-9]*[,])?[0-9]+$/;
const DECIMAL_DOT_SEPARATOR_REGEX = /^[+-]?([0-9]*[.])?[0-9]+$/;

const INTEGER_REGEX = /^[+-]?[0-9]+$/;
const NUMBER_REGEX = /^[+-]?([0-9]*[,.])?[0-9]+([eE][+-]?\d+)?$/;

const TRUE_REGEX = /^true$/i;
const FALSE_REGEX = /^false$/i;
Expand Down Expand Up @@ -47,24 +44,32 @@ class InternalRepresentationParserVisitor extends ValuetypeVisitor<
}

visitDecimal(): number | undefined {
let sanitizedValue: string;
if (DECIMAL_COMMA_SEPARATOR_REGEX.test(this.value)) {
sanitizedValue = this.value.replace(',', '.');
} else if (DECIMAL_DOT_SEPARATOR_REGEX.test(this.value)) {
sanitizedValue = this.value;
} else {
if (!NUMBER_REGEX.test(this.value)) {
return undefined;
}

return Number.parseFloat(sanitizedValue);
return Number.parseFloat(this.value.replace(',', '.'));
}

visitInteger(): number | undefined {
if (!INTEGER_REGEX.test(this.value)) {
/**
* Reuse decimal number parsing to capture valid scientific notation
* of integers like 5.3e3 = 5300. In contrast to decimal, if the final number
* is not a valid integer, returns undefined.
*/
Comment on lines +55 to +59
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love it!

const decimalNumber = this.visitDecimal();

if (decimalNumber === undefined) {
return undefined;
}

const integerNumber = Math.trunc(decimalNumber);

if (decimalNumber !== integerNumber) {
return undefined;
}

return Number.parseInt(this.value, 10);
return integerNumber;
}

visitText(): string {
Expand Down
Loading