diff options
author | Martin Fischer <martin@push-f.com> | 2021-02-28 09:18:48 +0100 |
---|---|---|
committer | Martin Fischer <martin@push-f.com> | 2021-03-03 12:52:46 +0100 |
commit | 4d43e952fff25b5b131e8699858da663a5ac2c42 (patch) | |
tree | acff62119061480a1cd7580f25c16c539aabc2ae /assets/script.js |
initial commit
Diffstat (limited to 'assets/script.js')
-rw-r--r-- | assets/script.js | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/assets/script.js b/assets/script.js new file mode 100644 index 0000000..4b4b5c5 --- /dev/null +++ b/assets/script.js @@ -0,0 +1,48 @@ +const searchInput = document.getElementById('search'); +const suggestionsDiv = document.getElementById('suggestions'); + +(async function(){ + const res = await fetch('/laws.json'); + const laws = await res.json(); + searchInput.addEventListener('input', (e) => { + if (searchInput.value == '') { + suggestionsDiv.innerHTML = ''; + return; + } + + const titleRegex = new RegExp(searchInput.value, 'i'); + const abbrRegex = new RegExp('^' + searchInput.value, 'i'); + const suggestions = []; + + laws.map(l => { + const titleMatch = titleRegex.exec(l.title); + const abbrMatch = abbrRegex.exec(l.abbr); + + return { + law: l, + titleScore: titleMatch ? titleMatch.index : Number.MAX_VALUE, + abbrScore: abbrMatch ? abbrMatch.index: Number.MAX_VALUE, + } + }) + .filter(l => l.titleScore < Number.MAX_VALUE || l.abbrScore < Number.MAX_VALUE) + .sort((a,b) => { + let abbrDiff = a.abbrScore - b.abbrScore; + if (a.law.abbr && b.law.abbr && abbrDiff == 0 && a.abbrScore != Number.MAX_VALUE) { + abbrDiff = a.law.abbr.length - b.law.abbr.length; + } + return abbrDiff || a.titleScore - b.titleScore; + }) + .slice(0, 30) + .forEach(x => { + const l = x.law; + const a = document.createElement('a'); + a.href = l.url; + a.textContent = l.title; + const li = document.createElement('li'); + li.appendChild(a); + suggestions.push(li); + }); + + suggestionsDiv.replaceChildren(...suggestions); + }); +})(); |