Skip to content

Commit 0093cda

Browse files
committed
Refactor for readability
1 parent ecc7934 commit 0093cda

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

packages/autocomplete-client/src/search/fetchMeilisearchResults.ts

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -72,27 +72,16 @@ export function fetchMeilisearchResults<TRecord = Record<string, any>>({
7272
| [keyof TRecord, Array<{ value: string }>] // if the field is an array
7373
>
7474
).reduce((acc, [field, highlightResult]) => {
75-
// if the field is an array, highlightResult is an array of objects
76-
if (Array.isArray(highlightResult)) {
77-
return {
78-
...acc,
79-
[field]: highlightResult.map((highlight) =>
80-
calculateHighlightMetadata(
81-
query.query || '',
82-
query.params?.highlightPreTag || HIGHLIGHT_PRE_TAG,
83-
query.params?.highlightPostTag || HIGHLIGHT_POST_TAG,
84-
highlight.value
85-
)
86-
),
87-
}
88-
}
8975
return {
9076
...acc,
91-
[field]: calculateHighlightMetadata(
92-
query.query || '',
93-
query.params?.highlightPreTag || HIGHLIGHT_PRE_TAG,
94-
query.params?.highlightPostTag || HIGHLIGHT_POST_TAG,
95-
highlightResult.value
77+
// if the field is an array, highlightResult is an array of objects
78+
[field]: mapOneOrMany(highlightResult, (highlightResult) =>
79+
calculateHighlightMetadata(
80+
query.query || '',
81+
query.params?.highlightPreTag || HIGHLIGHT_PRE_TAG,
82+
query.params?.highlightPostTag || HIGHLIGHT_POST_TAG,
83+
highlightResult.value
84+
)
9685
),
9786
}
9887
}, {} as HighlightResult<TRecord>),
@@ -153,3 +142,8 @@ function calculateHighlightMetadata(
153142
matchedWords: matches,
154143
}
155144
}
145+
146+
// Helper to apply a function to a single value or an array of values
147+
function mapOneOrMany<T, U>(value: T | T[], mapFn: (value: T) => U): U | U[] {
148+
return Array.isArray(value) ? value.map(mapFn) : mapFn(value)
149+
}

0 commit comments

Comments
 (0)