Skip to content

Commit f3329ac

Browse files
committed
Avoid re-sorting the options on every autocomplete
1 parent 5f13c86 commit f3329ac

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

src/labs/ia-combo-box/ia-combo-box.ts

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,13 @@ export class IAComboBox extends LitElement {
261261
*/
262262
private optionFilteringValues: Map<IAComboBoxOption, string> = new Map();
263263

264+
/**
265+
* A cache of the current set of options that is pre-sorted if the component's
266+
* `sort` flag is set, or as provided otherwise. Just ensures we don't have to
267+
* sort all the options again every time we filter them.
268+
*/
269+
private optionsRespectingSortFlag: IAComboBoxOption[] = [];
270+
264271
/**
265272
* A cache of the current set of filtered options, so that we don't have to
266273
* recalculate it unnecessarily whenever the component is opened/closed/etc.
@@ -303,6 +310,11 @@ export class IAComboBox extends LitElement {
303310
this.rebuildOptionIDMap();
304311
}
305312

313+
if (changed.has('options') || changed.has('sort')) {
314+
// Sort the options upfront if needed
315+
this.rebuildSortedOptions();
316+
}
317+
306318
if (
307319
hasAnyOf(changed, [
308320
'options',
@@ -943,6 +955,22 @@ export class IAComboBox extends LitElement {
943955
}
944956
}
945957

958+
/**
959+
* Applies any required sort to the options and caches the result to be used
960+
* at filter/display time.
961+
*/
962+
private rebuildSortedOptions(): void {
963+
if (this.sort) {
964+
this.optionsRespectingSortFlag = this.options.sort((a, b) => {
965+
const aValue = this.optionFilteringValues.get(a) as string;
966+
const bValue = this.optionFilteringValues.get(b) as string;
967+
return aValue.localeCompare(bValue);
968+
});
969+
} else {
970+
this.optionsRespectingSortFlag = this.options;
971+
}
972+
}
973+
946974
/**
947975
* Clears any previously-cached option filtering values, and rebuilds the
948976
* map based on the current component properties.
@@ -971,7 +999,7 @@ export class IAComboBox extends LitElement {
971999
? FILTER_PRESETS[resolvedFilterOption]
9721000
: resolvedFilterOption;
9731001

974-
const filtered = this.options
1002+
const filtered = this.optionsRespectingSortFlag
9751003
.filter((opt) => {
9761004
const optionFilteringValue = this.optionFilteringValues.get(opt);
9771005
if (!optionFilteringValue) return false;
@@ -980,14 +1008,6 @@ export class IAComboBox extends LitElement {
9801008
})
9811009
.slice(0, this.maxAutocompleteEntries);
9821010

983-
if (this.sort) {
984-
filtered.sort((a, b) => {
985-
const aValue = this.optionFilteringValues.get(a) as string;
986-
const bValue = this.optionFilteringValues.get(b) as string;
987-
return aValue.localeCompare(bValue);
988-
});
989-
}
990-
9911011
this.filteredOptions = filtered;
9921012
}
9931013

0 commit comments

Comments
 (0)