Skip to content

Commit

Permalink
Better array mapping handling
Browse files Browse the repository at this point in the history
  • Loading branch information
arlm committed Sep 20, 2022
1 parent 8d76492 commit dc6e381
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 6 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Expand Up @@ -2,3 +2,5 @@ out
node_modules
generated
coverage
vscode-antlr4-*.vsix
.antlr
34 changes: 29 additions & 5 deletions src/backend/SentenceGenerator.ts
Expand Up @@ -249,12 +249,23 @@ export class SentenceGenerator {
return ["", false];
}

const mapping = this.ruleMappings?.[ruleName];
if (mapping) {
const mappingValue = this.ruleMappings?.[ruleName];
if (mappingValue) {
let mapping: string | undefined;
if (Array.isArray(mapping)) {
const randomElement = mapping[Math.floor(Math.random() * mapping.length)];
return [addSpace ? randomElement + " " : randomElement, false];
if (mapping.length < 0) {
const randomIndex = Math.floor(Math.random() * mapping.length);
const randomElement = mapping[randomIndex];

mapping = randomElement;
} else if (mapping.length === 1) {
mapping = mapping[0];
}
} else {
mapping = mappingValue as string;
}

if (mapping) {
return [addSpace ? mapping + " " : mapping, false];
}
}
Expand Down Expand Up @@ -366,7 +377,20 @@ export class SentenceGenerator {
// its name for the output.
const tokenName = this.lexerData.vocabulary.getSymbolicName(token);
if (tokenName) {
const mapping = this.ruleMappings?.[tokenName];
const mappingValue = this.ruleMappings?.[tokenName];
let mapping: string | undefined;

if (Array.isArray(mappingValue)) {
if (mappingValue.length < 0) {
const randomIndex = Math.floor(Math.random() * mappingValue.length);
mapping = mappingValue[randomIndex];
} else if (mappingValue.length === 1) {
mapping = mappingValue[0];
}
} else if (mappingValue) {
mapping = mappingValue;
}

if (mapping) {
result += addSpace ? mapping + " " : mapping;
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/backend/types.ts
Expand Up @@ -265,7 +265,7 @@ export interface ISentenceGenerationOptions {
* Mappings from rule names to strings, which define output to use for specific rules when generating sentences.
*/
export interface IRuleMappings {
[key: string]: string;
[key: string]: string | string[];
}

/**
Expand Down

0 comments on commit dc6e381

Please sign in to comment.