This repository has been archived by the owner on Sep 10, 2024. It is now read-only.
forked from SJaved0327/frontend-exercise-public
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathAutocomplete.js
80 lines (65 loc) · 2 KB
/
Autocomplete.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
export default class Autocomplete {
constructor(rootEl, options = {}) {
options = Object.assign({ numOfResults: 10, data: [] }, options);
Object.assign(this, { rootEl, options });
this.init();
}
onQueryChange(query) {
// Get data for the dropdown
let results = this.getResults(query, this.options.data);
results = results.slice(0, this.options.numOfResults);
this.updateDropdown(results);
}
/**
* Given an array and a query, return a filtered array based on the query.
*/
getResults(query, data) {
if (!query) return [];
// Filter for matching strings
let results = data.filter((item) => {
return item.text.toLowerCase().includes(query.toLowerCase());
});
return results;
}
updateDropdown(results) {
this.listEl.innerHTML = '';
this.listEl.appendChild(this.createResultsEl(results));
}
createResultsEl(results) {
const fragment = document.createDocumentFragment();
results.forEach((result) => {
const el = document.createElement('li');
Object.assign(el, {
className: 'result',
textContent: result.text,
});
// Pass the value to the onSelect callback
el.addEventListener('click', (event) => {
const { onSelect } = this.options;
if (typeof onSelect === 'function') onSelect(result.value);
});
fragment.appendChild(el);
});
return fragment;
}
createQueryInputEl() {
const inputEl = document.createElement('input');
Object.assign(inputEl, {
type: 'search',
name: 'query',
autocomplete: 'off',
});
inputEl.addEventListener('input', event =>
this.onQueryChange(event.target.value));
return inputEl;
}
init() {
// Build query input
this.inputEl = this.createQueryInputEl();
this.rootEl.appendChild(this.inputEl)
// Build results dropdown
this.listEl = document.createElement('ul');
Object.assign(this.listEl, { className: 'results' });
this.rootEl.appendChild(this.listEl);
}
}