-
Notifications
You must be signed in to change notification settings - Fork 14
/
script.js
1590 lines (1256 loc) · 46.4 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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// <----------------- Dropdown Functionality ----------------->
// Accessing the dropdown elements
const companySelect = document.getElementById("company-select");
const durationSelect = document.getElementById("duration-select");
const sortSelect = document.getElementById("sort-select");
const difficultyFilter = document.getElementById("difficulty-filter");
const currentSelection = document.getElementById("current-selection");
// Event listener to handle the dropdown selection
document.addEventListener("DOMContentLoaded", function () {
fetch("company_data.json")
.then((response) => response.json())
.then((data) => initializeDropdowns(data))
.catch((error) => console.error("Error loading company data:", error));
});
// Function to initialize the dropdowns
function initializeDropdowns(companyData) {
Object.keys(companyData).forEach((company) => {
const option = document.createElement("option");
option.value = company;
option.textContent = company.charAt(0).toUpperCase() + company.slice(1);
companySelect.appendChild(option);
});
companySelect.addEventListener("change", function () {
const selectedCompany = companySelect.value;
const durations = companyData[selectedCompany];
durationSelect.innerHTML = '<option value="">Select Duration</option>';
durations.forEach((duration) => {
const option = document.createElement("option");
option.value = duration;
option.textContent = formatDuration(duration);
durationSelect.appendChild(option);
});
updateCompanyLogo(selectedCompany);
});
function updateDisplay() {
const company = companySelect.value;
const duration = durationSelect.value;
const sort = sortSelect.value;
const difficulty = difficultyFilter.value;
const logoImg = document.getElementById("company-logo");
const currentSelection = document.getElementById("current-selection");
if (company && duration) {
currentSelection.textContent = `${
company.charAt(0).toUpperCase() + company.slice(1)
} - ${formatDuration(duration)} Problems`;
updateCompanyLogo(company);
loadCompanyQuestions(company, duration, sort, difficulty);
} else {
logoImg.style.display = "none";
currentSelection.textContent = "";
clearTable();
}
}
companySelect.addEventListener("change", updateDisplay);
durationSelect.addEventListener("change", updateDisplay);
sortSelect.addEventListener("change", updateDisplay);
difficultyFilter.addEventListener("change", updateDisplay);
}
// <----------------- Company Logo Functionality ----------------->
// Function to update the company logo
function updateCompanyLogo(companyName) {
const logoImg = document.getElementById("company-logo");
logoImg.src = `https://logo.clearbit.com/${companyName}.com`;
logoImg.style.display = "block";
}
// Function to load the company questions
function loadCompanyQuestions(company, duration, sort, difficulty) {
const csvFile = `data/LeetCode-Questions-CompanyWise/${company}_${duration}.csv`;
fetch(csvFile)
.then((response) => response.text())
.then((csvText) => {
displayTable(csvText, sort, difficulty);
})
.catch((error) => console.error("Failed to load data:", error));
}
// <----------------- Table Display and Manipulation Functionality ----------------->
// Function to display the table when company and time are selected
function displayTable(csvData, sort, difficulty) {
// Get the container for the table
const tableContainer = document.getElementById("table-container");
if (tableContainer.innerHTML == "") {
if (window.problemsSolvedPerDayChart) {
window.problemsSolvedPerDayChart.destroy();
}
if (window.problemsSolvedByHourChart) {
window.problemsSolvedByHourChart.destroy();
}
}
tableContainer.innerHTML = ""; // Clear previous content
// Split CSV data into rows and filter out any empty rows
let rows = csvData.split("\n").filter((row) => row.trim());
// console.log("Rows", rows);
// Extract the header row
const header = rows.shift();
rows.unshift(header + ",Attempted?,Date Solved");
// header += ",Attempted,Date Solved";
// console.log("Header", header);
// Sort rows if sort option is provided
if (sort) {
rows = sortRows(rows, sort, header);
}
// Filter rows by difficulty if the difficulty filter is applied
if (difficulty) {
rows = filterRows(rows, difficulty, header);
}
// Reinsert the header at the beginning of the rows array
// Create a new table element
const table = document.createElement("table");
table.classList.add("styled-table"); // Apply custom table styles
let checkboxCount = 0; // Counter for the checkboxes
// Iterate over each row to create table rows
rows.forEach((row, index) => {
const tr = document.createElement("tr");
const cells = row.split(",");
if (index > 0) {
cells.push(""); // For 'Attempted' checkbox
cells.push(""); // For 'Date Solved' input
}
cells.forEach((cell, cellIndex) => {
const cellElement = document.createElement(index === 0 ? "th" : "td");
cellElement.classList.add("border", "px-4", "py-2", "text-center"); // Apply Tailwind CSS classes
if (index === 0) {
cellElement.style.backgroundColor = "#009879"; // Header cells background color
cellElement.style.color = "white";
}
if (index === 0 && cellIndex === cells.length - 2) {
// Set text for 'Attempted' header
cellElement.textContent = "Attempted?";
} else if (index === 0 && cellIndex === cells.length - 1) {
// Set text for 'Attempted' header
cellElement.textContent = "Date Solved";
} else if (index > 0 && cellIndex === cells.length - 2) {
// Checkbox for 'Attempted'
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.classList.add("form-checkbox", "h-5", "w-5", "text-blue-600");
checkbox.id = `attempt-${cells[0]}`;
checkbox.checked = JSON.parse(
localStorage.getItem(checkbox.id) || "false"
);
if (checkbox.checked) {
checkboxCount++; // count the already checked boxes
}
checkbox.addEventListener("change", function () {
const dateInput = document.getElementById(`date-${cells[0]}`);
if (this.checked) {
const currentDate = formatDate(new Date());
dateInput.value = currentDate;
localStorage.setItem(`date-${cells[0]}`, currentDate);
localStorage.setItem(`attempt-${cells[0]}`, this.checked);
checkboxCount++; // if checked, increment the counter
} else {
dateInput.value = "";
localStorage.removeItem(`date-${cells[0]}`);
localStorage.removeItem(`attempt-${cells[0]}`);
checkboxCount--; // if unchecked, decrement the counter
}
updateProgress(); // Update the progress bar
});
const label = document.createElement("label");
label.classList.add("inline-flex", "justify-center", "items-center");
label.appendChild(checkbox);
cellElement.appendChild(label);
} else if (index > 0 && cellIndex === cells.length - 1) {
// Input for 'Date Solved'
const dateInput = document.createElement("input");
dateInput.type = "text";
dateInput.id = `date-${cells[0]}`;
dateInput.classList.add("form-input", "text-center");
dateInput.value = localStorage.getItem(`date-${cells[0]}`) || "";
dateInput.disabled = true; // Disable the input field, can't change the date now
dateInput.addEventListener("change", function () {
localStorage.setItem(this.id, this.value);
});
cellElement.appendChild(dateInput);
} else if (index > 0 && cellIndex === 5) {
// Handling link cells
cellElement.style.display = "flex";
cellElement.style.flexDirection = "row-reverse";
cellElement.style.justifyContent = "space-around";
const link = document.createElement("a");
link.href = cell;
link.target = "_blank";
const leetCodeIcon = new Image();
leetCodeIcon.src = "leetcode.svg";
leetCodeIcon.alt = "LeetCode";
leetCodeIcon.style.alignItems = "center";
leetCodeIcon.style.height = "47px";
leetCodeIcon.style.width = "30px";
link.appendChild(leetCodeIcon);
cellElement.appendChild(link);
} else if (cellIndex === 3) {
// Special formatting for the Difficulty column
const difficultyTag = document.createElement("span");
difficultyTag.classList.add("difficulty-tag");
if (cell === "Easy") {
difficultyTag.classList.add("difficulty-easy");
} else if (cell === "Medium") {
difficultyTag.classList.add("difficulty-medium");
} else if (cell === "Hard") {
difficultyTag.classList.add("difficulty-hard");
}
difficultyTag.textContent = cell;
cellElement.appendChild(difficultyTag);
} else if (index > 0 && cellIndex === 4) {
// Formatting for frequency cells
cellElement.textContent = `${parseFloat(cell).toFixed(2)}%`;
} else {
// Normal cell handling
cellElement.textContent = cell;
}
tr.appendChild(cellElement);
});
table.appendChild(tr);
});
// Create a div to display the number of questions
const rowCountDisplay = document.createElement("div");
rowCountDisplay.className = "row-count-display"; // Assign the class to the div
// Create a container for the image and text
const contentContainer = document.createElement("div");
contentContainer.className = "content-container"; // New container for flex alignment
// Create the image element
const img = document.createElement("img");
img.src =
"https://cdn-icons-png.freepik.com/256/15441/15441427.png?semt=ais_hybrid";
img.alt = "Statistics Icon";
img.className = "row-count-icon"; // Assign a class for separate CSS styling
// Create the text content
const textContent = document.createElement("div");
textContent.className = "progress-text";
textContent.textContent = `Progress: ${checkboxCount} out of ${
rows.length - 1
} answered (${((checkboxCount / (rows.length - 1)) * 100).toFixed(2)}%)`;
// Append the image and text to the content container
contentContainer.appendChild(img);
contentContainer.appendChild(textContent);
// Create the text content (as tooltip text)
const tooltipText = document.createElement("span");
tooltipText.className = "tooltip-text";
let questionRemaining = rows.length - 1 - checkboxCount;
tooltipText.textContent = `${questionRemaining} ${
questionRemaining == 1 ? "question" : "questions"
} remaining`;
// Create the progress bar container
const progressBarContainer = document.createElement("div");
progressBarContainer.className = "progress-bar-container";
// Create the progress bar
const progressBar = document.createElement("div");
progressBar.className = "progress-bar";
// Set the progress bar width based on the percentage
const progressPercentage = (checkboxCount / (rows.length - 1)) * 100;
progressBar.style.width = `${progressPercentage}%`;
// Append elements to the display container
progressBarContainer.appendChild(progressBar);
rowCountDisplay.appendChild(contentContainer);
rowCountDisplay.appendChild(progressBarContainer);
rowCountDisplay.appendChild(tooltipText);
// Update the progress bar when the checkboxes are changed
function updateProgress() {
const totalQuestions = rows.length - 1;
const progressPercentage = (checkboxCount / totalQuestions) * 100;
progressBar.style.width = `${progressPercentage}%`;
textContent.textContent = `Progress: ${checkboxCount} out of ${totalQuestions} answered (${progressPercentage.toFixed(2)}%)`;
tooltipText.textContent = `${totalQuestions - checkboxCount} ${totalQuestions - checkboxCount === 1 ? "question" : "questions"} remaining`;
}
// Insert the row count above the table
tableContainer.insertBefore(rowCountDisplay, tableContainer.firstChild);
tableContainer.appendChild(table);
}
// Function to sort the rows based on the selected column
function sortRows(rows, sort, header) {
const headerParts = header.split(",");
const sortKey = sort.split("-")[0].trim();
// Adjust the sort key to match the header case
const capitalizedSortKey =
sortKey.charAt(0).toUpperCase() + sortKey.slice(1).toLowerCase();
const columnIndex = headerParts.indexOf(capitalizedSortKey);
if (columnIndex === -1) {
console.error("Sort key not found in header:", capitalizedSortKey);
return rows; // Return unsorted rows to prevent further errors
}
const difficultyOrder = { Easy: 1, Medium: 2, Hard: 3 };
const isAscending = sort.includes("asc"); // Determine sorting order
rows.sort((a, b) => {
let rowA = a.split(",");
let rowB = b.split(",");
let valA = rowA[columnIndex];
let valB = rowB[columnIndex];
if (valA === undefined || valB === undefined) {
console.error(
"Undefined value found for sort key",
capitalizedSortKey,
"at index",
columnIndex
);
return 0;
}
valA = valA.trim();
valB = valB.trim();
if (capitalizedSortKey === "Frequency") {
valA = parseFloat(valA);
valB = parseFloat(valB);
} else if (capitalizedSortKey === "Difficulty") {
valA = difficultyOrder[valA];
valB = difficultyOrder[valB];
}
if (valA < valB) {
return isAscending ? -1 : 1; // Adjust return based on sorting order
} else if (valA > valB) {
return isAscending ? 1 : -1; // Adjust return based on sorting order
}
return 0;
});
return rows;
}
// Define the filterRows function
function filterRows(rows, difficulty, header) {
// Find the index of the "Difficulty" column from the header
const headers = header.split(",");
const difficultyIndex = headers.indexOf("Difficulty");
// Return the header and rows where the difficulty matches
return rows.filter((row, index) => {
// Include the header row by default
if (index === 0) return true;
const cells = row.split(",");
// Compare the cell value with the desired difficulty
return cells[difficultyIndex] === difficulty;
});
}
// <----------------- Time Functionalities ----------------->
function formatDate(date) {
const nth = (d) => {
if (d > 3 && d < 21) return "th";
switch (d % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
};
let day = date.getDate();
let month = date.toLocaleString("default", { month: "long" });
let year = date.getFullYear();
let hour = date.getHours() % 12 || 12; // Convert to 12 hour format
let minute = date.getMinutes().toString().padStart(2, "0");
let ampm = date.getHours() >= 12 ? "PM" : "AM";
return `${day}${nth(day)} ${month} ${year}, ${hour}:${minute} ${ampm}`;
}
function formatDuration(duration) {
return duration
.replace("months", " Months")
.replace("year", " Year")
.replace("alltime", "All Time");
}
function isToday(date) {
const today = new Date();
return (
date.getDate() === today.getDate() &&
date.getMonth() === today.getMonth() &&
date.getFullYear() === today.getFullYear()
);
}
function isLast7Days(date, now) {
const oneWeekAgo = new Date(now);
oneWeekAgo.setDate(now.getDate() - 7);
return date >= oneWeekAgo && date <= now;
}
function isLastMonth(date, now) {
const oneMonthAgo = new Date(now);
oneMonthAgo.setMonth(now.getMonth() - 1);
return date >= oneMonthAgo && date <= now;
}
// Updated to format date strings for ChartJS
function parseDate(input) {
if (!input) {
return new Date();
}
const parts = input.match(
/(\d+)(st|nd|rd|th)? (\w+) (\d+), (\d+):(\d+) (AM|PM)/
);
if (!parts) return new Date(input); // Fallback to default parser if regex fails
const num = parseInt(parts[1], 10);
const month = parts[3];
const year = parseInt(parts[4], 10);
let hour = parseInt(parts[5], 10);
const minute = parseInt(parts[6], 10);
const ampm = parts[7];
if (ampm === "PM" && hour < 12) hour += 12;
if (ampm === "AM" && hour === 12) hour = 0;
return new Date(`${month} ${num}, ${year} ${hour}:${minute}:00`);
}
function getOrdinalSuffix(day) {
if (day > 3 && day < 21) return "th";
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
function formatDateWithEmoji(date) {
const nth = (d) => {
if (d > 3 && d < 21) return "th";
switch (d % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
};
const getTimeEmoji = (hour) => {
if (hour >= 5 && hour < 12) return "🌅"; // Morning
if (hour >= 12 && hour < 18) return "☀️"; // Afternoon
if (hour >= 18 && hour < 22) return "🌆"; // Evening
return "🌙"; // Night
};
let day = date.getDate();
let month = date.toLocaleString("default", { month: "long" });
let year = date.getFullYear();
let hour = date.getHours();
let minute = date.getMinutes().toString().padStart(2, "0");
let ampm = hour >= 12 ? "PM" : "AM";
let emoji = getTimeEmoji(hour);
hour = hour % 12 || 12; // Convert to 12 hour format
return `${emoji} ${day}${nth(
day
)} ${month} ${year}, ${hour}:${minute} ${ampm}`;
}
// <----------------- Search Functionality ----------------->
// Handling the search functionality
document.addEventListener('DOMContentLoaded', async () => {
try {
await loadAndSetIndex();
initializeSearchRecommendations();
} catch (error) {
console.error("Failed to initialize search:", error);
}
});
document.getElementById("search-button").addEventListener("click", () => {
const id = document.getElementById("id-search").value.trim();
if (id) {
searchByID(id);
}
});
// Event listener to handle "Enter" key in the input field
document.getElementById("id-search").addEventListener("keypress", (event) => {
if (event.key === "Enter") {
event.preventDefault(); // Prevent the default action to avoid submitting the form
const id = document.getElementById("id-search").value.trim();
if (id) {
searchByID(id);
}
}
});
function searchByID(id) {
fetch("preprocessed_companies.json")
.then((response) => response.json())
.then((data) => {
// If the question was asked in any company, then print the companies using the table
if (data[id]) {
const problem = data[id];
const title = problem.title;
const problemNameSlug = title.toLowerCase().replace(/ /g, "-");
const link = `https://leetcode.com/problems/${problemNameSlug}/description/`;
displaySearchResults(problem.companies, title, link);
} else {
// If the question was not asked in any company, then search in the problem data
return fetch("problem_data.json");
}
}).then((response) => {
if (response) return response.json();
}).then((problemData) => {
// The problem title is extracted from the problems dataset and then it is printed without companies.
if (problemData) {
const problem = problemData[id];
console.log(problem);
if (problem) {
const problemNameSlug = problem["name"].toLowerCase().replace(/ /g, "-");
const problemLink = `https://leetcode.com/problems/${problemNameSlug}/description/`;
displaySearchResults({}, problem["name"], problemLink);
}
}
}).catch((error) => console.error("Error loading data:", error));
}
// Preparing the data for the Search functionality
let searchIndex;
let searchArray = [];
async function loadAndSetIndex() {
try {
const response = await fetch("problem_data.json");
const data = await response.json();
searchIndex = data;
searchArray = Object.values(searchIndex);
return searchIndex;
} catch (error) {
console.error("Error loading search index:", error);
throw error;
}
}
// Add the recommendation UI and functionality
function initializeSearchRecommendations() {
const searchInput = document.getElementById('id-search');
const searchButton = document.getElementById('search-button');
let recommendationsContainer = null;
// Create recommendations container
function createRecommendationsContainer() {
const container = document.createElement('div');
container.className = 'absolute z-10 w-full bg-white border border-gray-300 rounded-md shadow-lg mt-1 max-h-60 overflow-y-auto';
container.style.top = '100%';
container.style.display = 'none';
searchInput.parentElement.appendChild(container);
return container;
}
// Create recommendation item
function createRecommendationItem(problem) {
const item = document.createElement('div');
item.className = 'px-4 py-2 hover:bg-gray-300 cursor-pointer flex items-center justify-between';
const leftContent = document.createElement('div');
leftContent.className = 'flex-1 text-black';
leftContent.textContent = problem.displayText;
const rightContent = document.createElement('div');
rightContent.className = `text-sm ${getDifficultyColor(problem.difficulty)}`;
rightContent.textContent = problem.difficulty;
item.appendChild(leftContent);
item.appendChild(rightContent);
item.addEventListener('click', () => {
searchInput.value = problem.id;
hideRecommendations();
searchButton.click();
});
return item;
}
// Get color class based on difficulty
function getDifficultyColor(difficulty) {
switch (difficulty.toLowerCase()) {
case 'easy': return 'text-green-600';
case 'medium': return 'text-yellow-600';
case 'hard': return 'text-red-600';
default: return 'text-gray-600';
}
}
// Show recommendations
function showRecommendations(recommendations) {
if (!recommendationsContainer) {
recommendationsContainer = createRecommendationsContainer();
}
recommendationsContainer.innerHTML = '';
if (recommendations.length === 0) {
const noResults = document.createElement('div');
noResults.className = 'px-4 py-2 text-gray-500';
noResults.textContent = 'No matching problems found';
recommendationsContainer.appendChild(noResults);
} else {
// Show all recommendations instead of limiting to 5
recommendations.forEach(problem => {
recommendationsContainer.appendChild(createRecommendationItem(problem));
});
}
recommendationsContainer.style.display = 'block';
}
// Hide recommendations
function hideRecommendations() {
if (recommendationsContainer) {
recommendationsContainer.style.display = 'none';
}
}
// Filter problems based on input
function filterProblems(query) {
query = query.toLowerCase();
return searchArray.filter(problem => {
return problem.id.includes(query) ||
problem.name.toLowerCase().includes(query) ||
problem.displayText.toLowerCase().includes(query);
});
}
// Add event listeners
searchInput.addEventListener('input', (e) => {
const query = e.target.value.trim();
if (query) {
const recommendations = filterProblems(query);
showRecommendations(recommendations);
} else {
hideRecommendations();
}
});
// Close recommendations when clicking outside
document.addEventListener('click', (e) => {
if (!searchInput.contains(e.target) && !recommendationsContainer?.contains(e.target)) {
hideRecommendations();
}
});
// Handle keyboard navigation
searchInput.addEventListener('keydown', (e) => {
if (!recommendationsContainer || recommendationsContainer.style.display === 'none') return;
const items = recommendationsContainer.children;
const currentIndex = Array.from(items).findIndex(item => item.classList.contains('bg-gray-300'));
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
if (currentIndex < items.length - 1) {
items[currentIndex]?.classList.remove('bg-gray-300');
items[currentIndex + 1].classList.add('bg-gray-300');
items[currentIndex + 1].scrollIntoView({ block: 'nearest' });
}
break;
case 'ArrowUp':
e.preventDefault();
if (currentIndex > 0) {
items[currentIndex]?.classList.remove('bg-gray-300');
items[currentIndex - 1].classList.add('bg-gray-300');
items[currentIndex - 1].scrollIntoView({ block: 'nearest' });
}
break;
case 'Enter':
if (currentIndex !== -1) {
e.preventDefault();
items[currentIndex].click();
}
break;
case 'Escape':
hideRecommendations();
break;
}
});
}
function displaySearchResults(data, title, link) {
const tableContainer = document.getElementById("table-container");
tableContainer.innerHTML = "";
const titleLinkContainer = document.createElement("div");
titleLinkContainer.style.display = "flex";
titleLinkContainer.style.alignItems = "center";
titleLinkContainer.style.justifyContent = "center";
titleLinkContainer.style.marginBottom = "10px";
const titleElement = document.createElement("h2");
titleElement.textContent = title;
titleElement.style.fontSize = "30px";
titleElement.style.marginRight = "10px";
const titleCheckbox = document.createElement("input");
titleCheckbox.type = "checkbox";
titleCheckbox.id = "title-checkbox";
titleCheckbox.classList.add(
"form-checkbox",
"h-5",
"w-5",
"text-blue-600",
"mr-2"
);
const checkboxId = parseInt(document.getElementById("id-search").value);
function getLocalStorageItem(key, checkboxId, defaultValue = false) {
let checkAttempted = localStorage.getItem(`${key}-${checkboxId}`);
return JSON.parse(checkAttempted || defaultValue);
}
titleCheckbox.checked = getLocalStorageItem("attempt", checkboxId);
titleCheckbox.addEventListener("change", function () {
if (this.checked) {
localStorage.setItem(`attempt-${checkboxId}`, this.checked);
const currentDate = formatDate(new Date());
localStorage.setItem(`date-${checkboxId}`, currentDate);
} else {
localStorage.removeItem(`attempt-${checkboxId}`);
localStorage.removeItem(`date-${checkboxId}`);
localStorage.removeItem(`companies-${checkboxId}`);
}
});
const linkElement = document.createElement("a");
if (link) {
linkElement.href = link;
linkElement.target = "_blank";
linkElement.style.display = "inline-flex";
linkElement.style.alignItems = "center";
linkElement.style.textDecoration = "none";
const leetCodeIcon = new Image();
leetCodeIcon.src = "leetcode.svg";
leetCodeIcon.alt = "LeetCode";
leetCodeIcon.style.height = "34px";
leetCodeIcon.style.width = "34px";
leetCodeIcon.style.marginRight = "5px";
leetCodeIcon.style.backgroundColor = "white";
leetCodeIcon.style.borderRadius = "50%";
leetCodeIcon.style.padding = "5px";
leetCodeIcon.style.display = "flex";
leetCodeIcon.style.justifyContent = "center";
leetCodeIcon.style.alignItems = "center";
leetCodeIcon.style.boxSizing = "border-box";
linkElement.insertBefore(leetCodeIcon, linkElement.firstChild);
}
titleLinkContainer.appendChild(titleCheckbox);
titleLinkContainer.appendChild(titleElement);
titleLinkContainer.appendChild(linkElement);
tableContainer.appendChild(titleLinkContainer);
// If no company asked that questions, simply print the title and link
if (Object.keys(data).length === 0) {
const noDataMsg = document.createElement("p");
noDataMsg.textContent = "The question was not asked in any company.";
noDataMsg.style.textAlign = "center";
noDataMsg.style.fontSize = "20px";
tableContainer.appendChild(noDataMsg);
return;
}
const companyCount = document.createElement("p");
companyCount.textContent = `Number of companies: ${Object.keys(data).length}`;
companyCount.style.textAlign = "center";
companyCount.style.fontSize = "20px";
tableContainer.appendChild(companyCount);
const table = document.createElement("table");
table.classList.add("styled-table");
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
// Create the header cells
["Company", "Frequency"].forEach(headerText => {
const header = document.createElement("th");
header.style.backgroundColor = "#556FB5";
header.style.color = "white";
header.textContent = headerText;
headerRow.appendChild(header);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// Making the body of the table where each company is shown
const tbody = document.createElement("tbody");
Object.entries(data).forEach(([company, frequencies]) => {
const row = document.createElement("tr"); // Create a new row
// Create the company cell
const companyNameCell = document.createElement("td");
companyNameCell.style.display = "flex";
companyNameCell.style.alignItems = "center";
const companyLogo = document.createElement("img");
companyLogo.src = `https://logo.clearbit.com/${company}.com`;
companyLogo.style.height = "24px";
companyNameCell.appendChild(companyLogo);
companyNameCell.appendChild(
document.createTextNode(
company.charAt(0).toUpperCase() + company.slice(1).toLowerCase()
)
);
row.appendChild(companyNameCell);
// Create the frequency cell
const frequencyCell = document.createElement("td");
const periods = {
"6months": "6 months",
"1year": "1 year",
"2year": "2 years",
"alltime": "all time"
};
Object.entries(frequencies).forEach(([period, frequency]) => {
const tag = document.createElement("span");
const percentageValue = Math.ceil(parseFloat(frequency) * 100);
tag.textContent = `${percentageValue}% (${periods[period]})`;
tag.classList.add("frequency-tag");
tag.style.marginRight = "10px";
if (percentageValue >= 70) {
tag.classList.add("high-frequency");
} else if (percentageValue >= 40) {
tag.classList.add("medium-frequency");
} else {
tag.classList.add("low-frequency");
}
frequencyCell.appendChild(tag);
});
row.appendChild(frequencyCell);
tbody.appendChild(row);
});
table.appendChild(tbody);
tableContainer.appendChild(table);
}
// <----------------- Clear Functionality ----------------->
function clearUIElements() {
// Clear the table
document.getElementById("table-container").innerHTML = "";
document.getElementById("current-selection").innerText = "";
document.getElementById("company-logo").style.display = "none";
document.getElementById("id-search").value = "";
document.getElementById("options").style.display = "none"; // Show the dropdown
document.getElementById("newEntryForm").classList.add("hidden");
document.getElementById("summaryTable").classList.add("hidden");
document.getElementById("uniqueId").value = "";
if (window.problemsSolvedPerDayChart) {
window.problemsSolvedPerDayChart.destroy();
}
if (window.problemsSolvedByHourChart) {
window.problemsSolvedByHourChart.destroy();
}
document.getElementById("company-select").selectedIndex = 0;
document.getElementById("duration-select").selectedIndex = 0;
document.getElementById("sort-select").selectedIndex = 0;
document.getElementById("difficulty-filter").selectedIndex = 0;
}
// Add the event listener to the clear button
document
.getElementById("clear-button")
.addEventListener("click", clearUIElements);
function clearTable() {
const tableContainer = document.getElementById("table-container");
tableContainer.innerHTML = "";
}