-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript-algos.html
307 lines (271 loc) · 10.1 KB
/
javascript-algos.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<h3>
Messages App
<button onclick="clearMessages()" id="clrbtn">
Clear Messages
</button>
</h3>
<div>
<!-- TODO ADD AN ATTRIBUTE THAT focuses the CURSOR INTO THE TEXTAREA ELEMENT WHEN THE PAGE LOADS -->
<textarea
autofocus
rows='6'
cols='55'
id="inputText"
type="text"
style="margin-bottom: 15px;" id="message" onkeyup="searchNames()">
</textarea>
<button onclick="addPlainMessage()">
Enter
</button>
</div>
<script>
function clearNames() {
var rootDiv = document.getElementById('listContainer');
if (rootDiv) {
while (rootDiv.hasChildNodes()) {
rootDiv.removeChild(rootDiv.lastChild);
}
}
}
function initDocument() {
clearNames();
initUsersNames();
initMessages();
}
function initUsersNames() {
var rootDiv = document.createElement('div');
rootDiv.id = 'listContainer';
var userNamesContainer = document.createElement('div');
userNames.forEach( function(userName, index) {
var childDiv = document.createElement('div');
var text = document.createTextNode(index.toString().concat(' .) ').concat(`${userName.firstName} ${userName.lastName}`));
childDiv.appendChild(text);
userNamesContainer.appendChild(childDiv);
});
rootDiv.appendChild(userNamesContainer);
document.body.appendChild(rootDiv);
}
function initMessages() {
var rootDiv = document.createElement('div');
var messagesContainer = document.createElement('div');
messagesContainer.id = 'messagesContainer';
messagesContainer.style['float'] = 'left';
document.body.appendChild(messagesContainer);
}
function clearMessages() {
/*TODO CLEAR MESSAGES FROM DOCUMENT WHEN USER CLICKS THE [CLEAR MESSAGES] BUTTON */
/* EXTRA CREDIT INCLUDE A SCRIPT TAG THATS FETCHES BOOTSTRAP CSS STLYINGS AND STYLE THE BUTTONS */
document.getElementById('messagesContainer').innerHTML = "";
document.getElementById('clrbtn').style.color = "red";
//document.getElementById('messagesContainer').style.color = "";
}
function addPlainMessage() {
const userText = getUserText();
var messagesContainer = document.getElementById('messagesContainer');
var messageDiv = document.createElement('p');
const text = document.createTextNode(userText);
messageDiv.appendChild(text);
messagesContainer.appendChild(messageDiv);
clearUserInput();
}
function addHandleMessage(handle) {
var messagesContainer = document.getElementById('messagesContainer');
var messageDiv = document.createElement('p');
var handleSpan = document.createElement('span');
handleSpan.style['color'] = 'dodgerblue';
handleText = document.createTextNode(handle);
handleSpan.appendChild(handleText);
// TODO:: EXCLUDING THE ORIGINALLY TYPED USER NAME REPLACE THIS TEXT \
// WITH ANY ADDITIONAL USER TEXT FROM THE ORIGIN USER TEXT MESSAGE
var dummyText = '';
var messageText = document.createTextNode(`${dummyText} `);
messageDiv.appendChild(handleSpan);
messageDiv.appendChild(messageText);
messagesContainer.appendChild(messageDiv);
clearFilteredNames();
clearUserInput();
}
//TODO SET THE FLAG TO FALS ONCE YOU UNDERSTAND THE ASSIGNMENT
const instructionsFlag = true;
if (instructionsFlag) {
console.log(`README`);
console.log(`
SETUP ->
1. INSTALL LODASH USING NPM AND SAVE THE DEPENDENCY TO YOUR PACKAGE.JSON FILE
2. IMPORT LODASH INTO THE INDEX.JS FILE.
3. COMPLETE ALL TODOS
`);
}
/* TODO ADD ADDITONALY
OBJECTS LIKE THE ONES BELOW, MINIMUM OF TEN.
EACH MUST CONTAIN A FIRST AND LAST NAME AND HANDLE */
const userNames = [
{
firstName: 'Chandler',
lastName: 'Gegg',
handle: '@CGegg'
},
{
firstName: 'Phil',
lastName: 'Mickelson',
handle: '@PMickelson'
},
{
firstName: 'Grace',
lastName: 'Hopper',
handle: '@GHopper'
},
{
firstName: 'Horace',
lastName: 'Grant',
handle: '@HGrant'
},
{
firstName: 'Alex',
lastName: 'Grant',
handle: '@AGrant'
},
{
firstName: 'Gwen',
lastName: 'Gude',
handle: '@GGude'
},
{
firstName: 'Brittany',
lastName: 'Brisher',
handle: '@GHopper'
},
{
firstName: 'Maddy',
lastName: 'Joy',
handle: '@MJoy'
},
{
firstName: 'Sam',
lastName: 'Joy',
handle: '@SJoy'
},
{
firstName: 'Sandy',
lastName: 'Petter',
handle: '@SPetter'
}
];
const userMessages = [];
const debounce = (func, delay) => {
let inDebounce
return function() {
const context = this
const args = arguments
clearTimeout(inDebounce)
inDebounce = setTimeout(() => func.apply(context, args), delay)
}
}
function initConstantTimeNameFileter() {
/* EXTRA CREDIT */
}
function constantTimeNameFilter(userText) {
/* EXTRA CREDIT :: CONVERT filterNames FUNCTION TO DO CONSTANT TIME LOOK UP.
THIS WILL REQUIRE initConstantTimeNameFileter ON PAGE LOAD AS WELL */
}
function filterNames(userText) {
const firstThreeChars = userText.toLowerCase().slice(1,4);
var re = new RegExp(firstThreeChars, 'g');
const filteredNames = [];
userNames.forEach( (userName) => {
const fullname = `${userName.firstName.toLowerCase()} ${userName.lastName.toLowerCase()}`;
var isMatch = !!userName.firstName.toLowerCase().match(re) || !!userName.lastName.toLowerCase().match(re);
console.log(`Fullname: ${fullname}` );
console.log(isMatch);
console.log(`Fullname: ${fullname}` );
if (isMatch) {
filteredNames.push(userName);
}
});
return filteredNames;
}
function initFilteredNames(filteredNames) {
clearNames();
var rootDiv = document.createElement('div');
rootDiv.id = 'filteredNamesContainer';
var namesContainer = document.createElement('div');
clearFilteredNames();
filteredNames.forEach( (name) => {
var nameElm = document.createElement('button');
var handleName= name.handle;
nameElm.style['background-color'] = 'dodgerblue';
nameElm.style['cursor'] = 'pointer';
nameElm.setAttribute('class', 'filtered-name');
nameElm.setAttribute('onClick', 'addName("'+handleName+'")');
nameElm.setAttribute('data-handle',handleName);
var text = document.createTextNode(`${name.firstName} ${name.lastName}`);
nameElm.appendChild(text);
namesContainer.appendChild(nameElm);
/*
TODO :: ADD CLICK EVENT LISTENER [addEventListener] TO EACH NAME ELEMENT.
IF THE USER CLICKS ON A FILTERED NAME THEN THEN A MESSAGE IS OUTPUT
USING THE ADD MESSAGE FUNCTION THAT REPLACES THE USER name WITH THE USER HANDLE.
THE addHandleMessage FUNCTION SHOULD BE INVOKED FROM INSIDE THE CALLBACK OF THE EVENT LISTENER.
TIPS:
BRUTE FORCE :: ASIGN A UNIQUE ID TO EACH NAME ELEMENT, GRAB ID FROM THE EVENT AND
PASS IT AS AN ARGUMENT TO ADD MESSAGE FUNCTION THEN SEARCH USER NAMES ARRAY
DATA ATTRIBUTE :: ASSIGN A DATA ATTRIBUTE CALLED [handle] TO EACH THE NAME ELEMENT
GRAB DATA ATTRIBUTE FROM THE EVENT AND PASS IT AS AN ARGUMENT TO
ADD MESSAGE FUNCTION THEN SEARCH USER NAMES ARRAY
EXAMPLE: @chandler => @CGegg
*/
//TODO WRAP THIS FUNCTION WITH EVENT LISTENER AND UNCOMMENT IT
//TODO REPLACE [myHandle] WITH THE USERS CORRECT HANDLE
// addHandleMessage('myHandle');
});
document.body.appendChild(namesContainer);
}
function clearUserInput() {
document.getElementById('inputText').value = '';
}
function clearFilteredNames() {
const filteredNames = document.getElementsByClassName('filtered-name');
Array.from(filteredNames).forEach( (filteredName) => {
filteredName.remove();
});
}
function getUserText() {
return document.getElementById('inputText').value.trim();
}
function searchNames() {
const userText = getUserText();
console.log('Search names ...');
console.log(userText);
console.log('Search names ...');
const firstChar = userText[0] || '';
if (firstChar === '@') {
console.log('filter names ...');
const filteredNames = filterNames(userText);
initFilteredNames(filteredNames);
} else {
console.log('MISSING @ IN USER TEXT');
}
}
// TODO UPDATE THE DEBOUNCE DELAY TO MORE CLOSELY RESEMBLE USER TYPING
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('inputText').addEventListener(
'input',
debounce(
searchNames,
20000
)
);
initDocument();
});
function addName(handleName){
document.getElementById('inputText').value=handleName;
}
</script>
<style>
.filtered-name {
border-radius: 5px;
height: 23px;
line-height: 18px;
}
</style>