-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
76 lines (51 loc) · 1.94 KB
/
script.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
'use strict';
document.addEventListener('DOMContentLoaded', initialize);
// ------------------------------------------------------------
function initialize() {
const input = document.querySelector('input');
const list = document.querySelector('ul');
const files = ['kennzeichen', 'laenderkennzeichen', 'diplomatenkennzeichen'];
const manager = new DirectoryManager(list);
Promise
.all(files.map(file => fetch(`data/${file}.json`)))
.then(responses => Promise.all(responses.map(response => response.json())))
.then(jsons => jsons.map(json => manager.addDirectory(new Directory(json))));
input.addEventListener('keyup', () => manager.render(input.value.trim().toUpperCase()));
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js', { scope: '.' });
}
}
// ------------------------------------------------------------
class DirectoryManager {
constructor(element) {
this.element = element;
this.directories = [];
this.emptyTemplate = `<li>keine Ergebnisse</li>`;
}
addDirectory(directory) {
this.directories.push(directory);
}
render(term) {
const invoke = (fn) => this.directories.map(directory => directory[fn](term)).join('');
this.element.innerHTML = invoke('search') || invoke('reverseSearch') || this.emptyTemplate;
}
}
// ------------------------------------------------------------
class Directory {
constructor(data) {
this.data = data;
}
search(term) {
const filter = (key) => key.startsWith(term);
return this.render(filter);
}
reverseSearch(term) {
const regexp = new RegExp(term, 'i');
const filter = (key) => this.data[key].match(regexp);
return this.render(filter);
}
render(filter) {
const template = (key) => `<li><strong>${key}</strong> ${this.data[key]}</li>`;
return Object.keys(this.data).filter(filter).map(template).join('');
}
}