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