| 502 | }); |
| 503 | |
| 504 | const scorePreparedField = ( |
| 505 | query: string, |
| 506 | queryTokens: readonly string[], |
| 507 | field: PreparedField, |
| 508 | weight: number, |
| 509 | ): { |
| 510 | readonly score: number; |
| 511 | readonly matchedTokens: ReadonlySet<string>; |
| 512 | readonly exactPhraseMatch: boolean; |
| 513 | } => { |
| 514 | if (field.raw.length === 0) { |
| 515 | return { |
| 516 | score: 0, |
| 517 | matchedTokens: new Set<string>(), |
| 518 | exactPhraseMatch: false, |
| 519 | }; |
| 520 | } |
| 521 | |
| 522 | let score = 0; |
| 523 | const matchedTokens = new Set<string>(); |
| 524 | const exactPhraseMatch = query.length > 0 && field.raw.includes(query); |
| 525 | |
| 526 | if (query.length > 0) { |
| 527 | if (field.raw === query) { |
| 528 | score += weight * 14; |
| 529 | } else if (field.raw.startsWith(query)) { |
| 530 | score += weight * 9; |
| 531 | } else if (exactPhraseMatch) { |
| 532 | score += weight * 6; |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | for (const token of queryTokens) { |
| 537 | if (field.tokens.includes(token)) { |
| 538 | score += weight * 4; |
| 539 | matchedTokens.add(token); |
| 540 | continue; |
| 541 | } |
| 542 | |
| 543 | if ( |
| 544 | field.tokens.some((candidate) => candidate.startsWith(token) || token.startsWith(candidate)) |
| 545 | ) { |
| 546 | score += weight * 2; |
| 547 | matchedTokens.add(token); |
| 548 | continue; |
| 549 | } |
| 550 | |
| 551 | if (field.raw.includes(token)) { |
| 552 | score += weight; |
| 553 | matchedTokens.add(token); |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | return { |
| 558 | score, |
| 559 | matchedTokens, |
| 560 | exactPhraseMatch, |
| 561 | }; |