-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.html
91 lines (88 loc) · 3.03 KB
/
demo.html
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
81
82
83
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>word list</title>
<style>
.warning {
color: red;
}
</style>
</head>
<body>
<div id="root">
<form id="input-form">
<input name="text" placeholder="new word" />
<input type="button" value="add" />
<input type="button" value="remove" />
</form>
<code id="warnings" class="warning"></code>
<br />
sort:
<select id="sort-type">
<option value="oldest">old -> new</option>
<option value="newest">new -> old</option>
<option value="a">a -> z</option>
<option value="z">z -> a</option>
<option value="shortest">short -> long</option>
<option value="longest">long -> short</option>
</select>
<div id="list-container"></div>
</div>
<script>
const isWord = (a = '') => /^[a-zA-Z]+$/.test(a),
sortStrings = (a = [], b = 'oldest') => {
let c;
return (
(c =
'newest' === b
? [...a].reverse()
: 'a' === b
? [...a].sort()
: 'z' === b
? [...a].sort().reverse()
: 'shortest' === b
? [...a].sort((c, a) => c.length - a.length)
: 'longest' === b
? [...a].sort((c, a) => c.length - a.length).reverse()
: [...a]),
c
);
},
data = { words: [], sort: 'oldest' },
handleInputWord = (a) => {
if ('button' !== a.target.type) return;
const b = a.target.form.text.value,
c = a.target.value,
d = document.getElementById('warnings');
if (((d.innerHTML = ''), 'add' === c)) {
if (!isWord(b)) return void (d.innerHTML = `"${b}" is not a word`);
data.words.push(b);
} else if ('remove' === c) {
if (!data.words.includes(b))
return void (d.innerHTML = `"${b}" is not in the list`);
data.words.splice(data.words.indexOf(b), 1);
}
const e = sortStrings(data.words, data.sort),
f = e.reduce((a, b) => `${a}<li>${b}</li>`, '');
document.getElementById('list-container').innerHTML = `<ul>${f}</ul>`;
},
handleSortWords = (a) => {
const b = a.target.value;
data.sort = b;
const c = sortStrings(data.words, data.sort),
d = c.reduce((a, b) => `${a}<li>${b}</li>`, '');
document.getElementById('list-container').innerHTML = `<ul>${d}</ul>`;
};
document
.getElementById('input-form')
.addEventListener('click', handleInputWord),
document
.getElementById('sort-type')
.addEventListener('change', handleSortWords);
const sortedLis = data.words.reduce((a, b) => `${a}<li>${b}</li>`, ''),
sortedList = `<ul>${sortedLis}</ul>`;
document.getElementById('list-container').innerHTML = sortedList;
</script>
</body>
</html>