Skip to content

Commit

Permalink
calcualte levenshtein distance for search results
Browse files Browse the repository at this point in the history
  • Loading branch information
nimarion committed Jun 19, 2024
1 parent 8fdeb46 commit a721635
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/athletes/athlete.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,9 @@ export class AthleteSearchResult {
sex: 'MALE' | 'FEMALE' | null;
@ApiProperty({ nullable: true, type: Date })
birthdate: Date | null;
@ApiProperty({
type: Number,
description: 'Levenshtein distance between search query and athlete name',
})
levenshteinDistance: number;
}
12 changes: 10 additions & 2 deletions src/athletes/athletes.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import parseVenue from './venue.utils';
import mapDisciplineToCode from 'src/discipline.utils';
import { formatLastname } from 'src/name.utils';
import { GraphqlService } from 'src/graphql/graphql.service';
import { levenshteinDistance } from 'src/levenshtein-distance';

@Injectable()
export class AthletesService {
Expand All @@ -27,7 +28,7 @@ export class AthletesService {
searchCompetitors: z.array(AthleteSearchSchema),
})
.parse(data);
return response.searchCompetitors.map((item) => {
const searchResults = response.searchCompetitors.map((item) => {
const sex =
item.gender === 'Men'
? 'MALE'
Expand All @@ -40,9 +41,16 @@ export class AthletesService {
firstname: item.givenName,
lastname: formatLastname(item.familyName),
birthdate: item.birthDate,
levenshteinDistance: levenshteinDistance(
name.toLowerCase().trim(),
(item.givenName + ' ' + item.familyName).toLowerCase().trim(),
),
sex,
};
});
}) as AthleteSearchResult[];
return searchResults.sort(
(a, b) => a.levenshteinDistance - b.levenshteinDistance,
);
} catch (error) {
console.error(error);
Sentry.captureException(error);
Expand Down
19 changes: 19 additions & 0 deletions src/levenshtein-distance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const levenshteinDistance = (s, t) => {
if (!s.length) return t.length;
if (!t.length) return s.length;
const arr = [];
for (let i = 0; i <= t.length; i++) {
arr[i] = [i];
for (let j = 1; j <= s.length; j++) {
arr[i][j] =
i === 0
? j
: Math.min(
arr[i - 1][j] + 1,
arr[i][j - 1] + 1,
arr[i - 1][j - 1] + (s[j - 1] === t[i - 1] ? 0 : 1),
);
}
}
return arr[t.length][s.length];
};

0 comments on commit a721635

Please sign in to comment.