server-ts: Port services/search/services/handle_parens

This commit is contained in:
Elian Doran 2024-02-18 01:38:51 +02:00
parent 8acb64198c
commit deed58c2fc
No known key found for this signature in database
3 changed files with 17 additions and 8 deletions

View File

@ -1,4 +1,4 @@
const handleParens = require('../../src/services/search/services/handle_parens.js');
const handleParens = require('../../src/services/search/services/handle_parens');
describe("Parens handler", () => {
it("handles parens", () => {

View File

@ -1,13 +1,17 @@
interface Token {
token: string;
}
/**
* This will create a recursive object from a list of tokens - tokens between parenthesis are grouped in a single array
*/
function handleParens(tokens) {
function handleParens(tokens: (Token | Token[])[]) {
if (tokens.length === 0) {
return [];
}
while (true) {
const leftIdx = tokens.findIndex(token => token.token === '(');
const leftIdx = tokens.findIndex(token => "token" in token && token.token === '(');
if (leftIdx === -1) {
return tokens;
@ -17,13 +21,18 @@ function handleParens(tokens) {
let parensLevel = 0
for (rightIdx = leftIdx; rightIdx < tokens.length; rightIdx++) {
if (tokens[rightIdx].token === ')') {
const token = tokens[rightIdx];
if (!("token" in token)) {
continue;
}
if (token.token === ')') {
parensLevel--;
if (parensLevel === 0) {
break;
}
} else if (tokens[rightIdx].token === '(') {
} else if (token.token === '(') {
parensLevel++;
}
}
@ -36,8 +45,8 @@ function handleParens(tokens) {
...tokens.slice(0, leftIdx),
handleParens(tokens.slice(leftIdx + 1, rightIdx)),
...tokens.slice(rightIdx + 1)
];
] as (Token | Token[])[];
}
}
module.exports = handleParens;
export = handleParens;

View File

@ -2,7 +2,7 @@
const normalizeString = require("normalize-strings");
const lex = require('./lex.js');
const handleParens = require('./handle_parens.js');
const handleParens = require('./handle_parens');
const parse = require('./parse.js');
const SearchResult = require('../search_result');
const SearchContext = require('../search_context');