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