Skip to content

Commit

Permalink
Refactor getReadingFromDefinition function to normalize text and use …
Browse files Browse the repository at this point in the history
…matchAll for bracket matching
  • Loading branch information
MarvNC committed Dec 23, 2023
1 parent 0f64cbe commit 6d3c5c9
Showing 1 changed file with 22 additions and 19 deletions.
41 changes: 22 additions & 19 deletions src/readingParse.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,31 @@ const leewayAfterTerm = 2;
* @returns {string}
*/
function getReadingFromDefinition(definition, term) {
const normalizeText = (text) => text.replace(/ /g, '').toLowerCase();
// Remove spaces from definition and term
definition = definition.replace(/ /g, '');
term = term.replace(/ /g, '');
const bracketRegex = /([((]([^))]*))/g;
const bracketMatches = bracketRegex.exec(definition);
definition = normalizeText(definition);
term = normalizeText(term);
const bracketRegex = /([((]([^))]*)[))])/g;
const bracketMatches = definition.matchAll(bracketRegex) ?? [];

if (bracketMatches && bracketMatches.length >= 2) {
// @ts-ignore
const outerBracketContent = bracketMatches[1];
const bracketContent = bracketMatches[2];
const bracketIndex = definition.indexOf(outerBracketContent);
const termIndex = definition.indexOf(term) ?? 0;
const termEndIndex = termIndex + term.length;
// If the bracket is not at the beginning of the definition or closely following the term, ignore it
if (bracketIndex - termEndIndex > leewayAfterTerm) {
return '';
for (const matchArr of bracketMatches) {
if (matchArr && matchArr.length >= 3) {
// @ts-ignore
const outerBracketContent = matchArr[1];
const bracketContent = matchArr[2];
const bracketIndex = definition.indexOf(outerBracketContent);
const termIndex = definition.indexOf(term) ?? 0;
const termEndIndex = termIndex + term.length;
// If the bracket is not at the beginning of the definition or closely following the term, ignore it
if (bracketIndex - termEndIndex > leewayAfterTerm) {
continue;
}
// If the bracket is within the term or before the term, ignore it
if (bracketIndex < termEndIndex) {
continue;
}
return parseReadingFromBrackets(bracketContent, term);
}
// If the bracket is within the term or before the term, ignore it
if (bracketIndex < termIndex) {
return '';
}
return parseReadingFromBrackets(bracketContent, term);
}
return '';
}
Expand Down

0 comments on commit 6d3c5c9

Please sign in to comment.