-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
64 lines (59 loc) · 1.58 KB
/
main.js
File metadata and controls
64 lines (59 loc) · 1.58 KB
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
let maxResults
const wordTree = {}
window.addEventListener("load", async () => {
const textInput = document.getElementById("text-input")
const resultUl = document.getElementById("result-ul")
maxResults = resultUl.childElementCount
fetch('./words.txt')
.then(res => res.text())
.then(text => text.split('\n'))
.then(wordsArray => buildWordTree(wordsArray))
.then(() => textInput.addEventListener("input", textListener))
.then(() => console.log('Word tree is built'))
.catch(error => console.log(error))
})
function buildWordTree(wordsArray) {
for (const word of wordsArray) {
let layer = wordTree
for (const c of word.toLowerCase()) {
if (!layer.hasOwnProperty(c)) {
layer[c] = {}
}
layer = layer[c]
}
layer["word"] = word
}
}
function textListener(e) {
const partialText = e.target.value
let layer = wordTree
for (const c of partialText) {
layer = layer[c]
if (layer === undefined) break
}
const done = []
if (layer === undefined) {
showResults(done)
return
}
active = Object.values(layer)
while (done.length < maxResults) {
if (active.length === 0) break
current = active.shift()
if (typeof current === 'string') {
done.push(current)
continue
}
active = active.concat(Object.values(current))
}
done.sort()
showResults(done)
}
function showResults(done) {
for (let i = 0; i < maxResults; i++) {
const result = done[i]
const li = document.getElementById(`li-${i}`)
if (li === null) continue
li.innerHTML = result === undefined ? "" : result
}
}