-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercises.html
More file actions
1146 lines (1063 loc) · 47.7 KB
/
exercises.html
File metadata and controls
1146 lines (1063 loc) · 47.7 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Exercises - Practice & Challenges</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'edu-blue': '#3B82F6',
'edu-green': '#10B981',
'edu-purple': '#8B5CF6',
'edu-yellow': '#F59E0B',
'edu-bg': '#F9FAFB',
'edu-text': '#374151'
}
}
}
}
</script>
<link rel="stylesheet" href="css/educational-theme.css">
<style>
.exercise-card {
transition: all 0.3s ease;
cursor: pointer;
}
.exercise-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}
.difficulty-easy {
background: linear-gradient(135deg, #10B981, #34D399);
}
.difficulty-medium {
background: linear-gradient(135deg, #F59E0B, #FBBF24);
}
.difficulty-hard {
background: linear-gradient(135deg, #EF4444, #F87171);
}
.code-editor {
background: #1F2937;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
color: #F9FAFB;
resize: vertical;
min-height: 250px;
width: 100%;
}
.output-panel {
background: #111827;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
color: #10B981;
min-height: 150px;
overflow-y: auto;
white-space: pre-wrap;
}
.test-result {
padding: 0.5rem;
margin: 0.25rem 0;
border-radius: 0.375rem;
font-family: monospace;
font-size: 0.875rem;
}
.test-pass {
background: #065F46;
color: #10B981;
border-left: 4px solid #10B981;
}
.test-fail {
background: #7F1D1D;
color: #F87171;
border-left: 4px solid #EF4444;
}
.exercise-modal {
display: none;
}
.exercise-modal.active {
display: flex;
}
.progress-bar {
background: #E5E7EB;
border-radius: 9999px;
height: 0.5rem;
overflow: hidden;
}
.progress-fill {
background: linear-gradient(90deg, #10B981, #3B82F6);
height: 100%;
transition: width 0.3s ease;
}
</style>
</head>
<body class="bg-edu-bg text-edu-text">
<!-- Navigation -->
<nav class="bg-white shadow-lg fixed w-full z-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<div class="flex-shrink-0 flex items-center">
<a href="index.html" class="flex items-center">
<span class="text-2xl font-bold text-edu-blue">JS</span>
<span class="text-2xl font-bold text-edu-purple ml-1">Learning Hub</span>
</a>
</div>
</div>
<div class="hidden md:flex items-center space-x-8">
<a href="index.html" class="text-gray-700 hover:text-edu-blue transition-colors">Home</a>
<a href="lessons.html" class="text-gray-700 hover:text-edu-blue transition-colors">Lessons</a>
<a href="playground.html" class="text-gray-700 hover:text-edu-blue transition-colors">Playground</a>
<a href="exercises.html" class="text-edu-blue font-semibold">Exercises</a>
</div>
</div>
</div>
</nav>
<!-- Header -->
<section class="pt-20 pb-12 bg-gradient-to-r from-edu-purple to-edu-blue">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center text-white">
<h1 class="text-4xl md:text-5xl font-bold mb-4">JavaScript Exercises</h1>
<p class="text-xl opacity-90 max-w-3xl mx-auto mb-6">
Test your skills with hands-on coding challenges. Practice makes perfect!
</p>
<!-- Progress Overview -->
<div class="bg-white bg-opacity-10 rounded-lg p-6 max-w-2xl mx-auto">
<div class="flex justify-between items-center mb-3">
<span class="text-sm font-medium">Overall Progress</span>
<span class="text-sm" id="progress-text">0 / 20 completed</span>
</div>
<div class="progress-bar">
<div class="progress-fill" id="progress-fill" style="width: 0%"></div>
</div>
</div>
</div>
</section>
<!-- Filter Section -->
<section class="py-8 bg-white border-b border-gray-200">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex flex-wrap items-center justify-between gap-4">
<div class="flex flex-wrap gap-3">
<button onclick="filterExercises('all')"
class="filter-btn active px-4 py-2 rounded-lg border border-gray-300 bg-edu-blue text-white font-medium">
All Exercises
</button>
<button onclick="filterExercises('easy')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Easy
</button>
<button onclick="filterExercises('medium')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Medium
</button>
<button onclick="filterExercises('hard')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Hard
</button>
</div>
<div class="flex items-center gap-3">
<span class="text-sm text-gray-600">Sort by:</span>
<select id="sort-select" onchange="sortExercises()"
class="border border-gray-300 rounded px-3 py-1 text-sm">
<option value="order">Default Order</option>
<option value="difficulty">Difficulty</option>
<option value="title">Title (A-Z)</option>
<option value="completed">Completion Status</option>
</select>
</div>
</div>
</div>
</section>
<!-- Exercises Grid -->
<section class="py-16">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6" id="exercises-grid">
<!-- Exercises will be populated by JavaScript -->
</div>
</div>
</section>
<!-- Exercise Modal -->
<div id="exercise-modal"
class="exercise-modal fixed inset-0 bg-black bg-opacity-50 items-center justify-center z-50">
<div class="bg-white rounded-lg max-w-7xl w-full mx-4 max-h-screen overflow-y-auto">
<!-- Modal Header -->
<div class="p-6 border-b border-gray-200 flex justify-between items-center">
<div>
<h2 id="modal-title" class="text-2xl font-bold text-gray-900"></h2>
<div class="flex items-center gap-3 mt-2">
<span id="modal-difficulty" class="px-3 py-1 rounded-full text-sm font-medium"></span>
<span id="modal-category" class="text-sm text-gray-600"></span>
</div>
</div>
<button id="close-modal" class="text-gray-500 hover:text-gray-700">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12">
</path>
</svg>
</button>
</div>
<!-- Modal Content -->
<div class="p-6">
<div class="grid lg:grid-cols-2 gap-6">
<!-- Problem Description -->
<div class="space-y-6">
<div>
<h3 class="text-lg font-semibold mb-3">📋 Problem Description</h3>
<div id="modal-description" class="text-gray-600 leading-relaxed"></div>
</div>
<div id="modal-examples" class="hidden">
<h3 class="text-lg font-semibold mb-3">💡 Examples</h3>
<div class="space-y-3"></div>
</div>
<div id="modal-hints" class="hidden">
<h3 class="text-lg font-semibold mb-3">💭 Hints</h3>
<div class="space-y-2"></div>
</div>
<div>
<h3 class="text-lg font-semibold mb-3">🧪 Test Results</h3>
<div id="test-results" class="space-y-2">
<div class="text-gray-500 text-sm">Run your code to see test results</div>
</div>
</div>
</div>
<!-- Code Editor -->
<div class="space-y-4">
<div>
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold">💻 Your Solution</h3>
<div class="flex gap-2">
<button onclick="showHints()"
class="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded transition-colors">
💡 Show Hints
</button>
<button onclick="resetCode()"
class="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded transition-colors">
🔄 Reset
</button>
</div>
</div>
<textarea id="code-editor" class="code-editor"
placeholder="Write your solution here..."></textarea>
</div>
<div class="flex gap-3">
<button onclick="runTests()"
class="bg-edu-blue text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition-colors">
▶ Run Tests
</button>
<button onclick="submitSolution()"
class="bg-edu-green text-white px-6 py-2 rounded-lg hover:bg-green-600 transition-colors">
✅ Submit Solution
</button>
</div>
<div>
<h3 class="text-lg font-semibold mb-3">📊 Output</h3>
<div id="output-panel" class="output-panel">
Click "Run Tests" to see your code output and test results.
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// Exercise data
const exercises = [
{
id: 'hello-world',
title: 'Hello World',
difficulty: 'easy',
category: 'Basic Syntax',
description: 'Write a function that returns the string "Hello, World!"',
examples: [
{ input: '', output: '"Hello, World!"' }
],
hints: [
'Use the return statement to return a value',
'Strings in JavaScript are enclosed in quotes'
],
starterCode: `function helloWorld() {
// Write your code here
}`,
solution: `function helloWorld() {
return "Hello, World!";
}`,
tests: [
{
name: 'Returns "Hello, World!"',
test: () => {
try {
const result = helloWorld();
return {
pass: result === "Hello, World!",
message: result === "Hello, World!" ? 'Correct!' : `Expected "Hello, World!" but got "${result}"`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
},
{
id: 'add-numbers',
title: 'Add Two Numbers',
difficulty: 'easy',
category: 'Math Operations',
description: 'Write a function that takes two numbers and returns their sum.',
examples: [
{ input: 'add(2, 3)', output: '5' },
{ input: 'add(-1, 1)', output: '0' },
{ input: 'add(0, 0)', output: '0' }
],
hints: [
'Use the + operator to add numbers',
'Function parameters are the values passed to the function'
],
starterCode: `function add(a, b) {
// Write your code here
}`,
solution: `function add(a, b) {
return a + b;
}`,
tests: [
{
name: 'Adds positive numbers',
test: () => {
try {
const result = add(2, 3);
return {
pass: result === 5,
message: result === 5 ? 'Correct!' : `Expected 5 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles negative numbers',
test: () => {
try {
const result = add(-1, 1);
return {
pass: result === 0,
message: result === 0 ? 'Correct!' : `Expected 0 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles zero',
test: () => {
try {
const result = add(0, 0);
return {
pass: result === 0,
message: result === 0 ? 'Correct!' : `Expected 0 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
},
{
id: 'even-odd',
title: 'Even or Odd',
difficulty: 'easy',
category: 'Conditionals',
description: 'Write a function that determines if a number is even or odd. Return "even" for even numbers and "odd" for odd numbers.',
examples: [
{ input: 'isEvenOrOdd(4)', output: '"even"' },
{ input: 'isEvenOrOdd(7)', output: '"odd"' },
{ input: 'isEvenOrOdd(0)', output: '"even"' }
],
hints: [
'Use the modulus operator (%) to check remainders',
'Even numbers have no remainder when divided by 2',
'Use if/else statements for conditional logic'
],
starterCode: `function isEvenOrOdd(number) {
// Write your code here
}`,
solution: `function isEvenOrOdd(number) {
if (number % 2 === 0) {
return "even";
} else {
return "odd";
}
}`,
tests: [
{
name: 'Identifies even numbers',
test: () => {
try {
const result = isEvenOrOdd(4);
return {
pass: result === "even",
message: result === "even" ? 'Correct!' : `Expected "even" but got "${result}"`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Identifies odd numbers',
test: () => {
try {
const result = isEvenOrOdd(7);
return {
pass: result === "odd",
message: result === "odd" ? 'Correct!' : `Expected "odd" but got "${result}"`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles zero correctly',
test: () => {
try {
const result = isEvenOrOdd(0);
return {
pass: result === "even",
message: result === "even" ? 'Correct!' : `Expected "even" but got "${result}"`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
},
{
id: 'reverse-string',
title: 'Reverse a String',
difficulty: 'medium',
category: 'String Manipulation',
description: 'Write a function that takes a string and returns it reversed.',
examples: [
{ input: 'reverseString("hello")', output: '"olleh"' },
{ input: 'reverseString("JavaScript")', output: '"tpircSavaJ"' },
{ input: 'reverseString("")', output: '""' }
],
hints: [
'You can convert a string to an array using split()',
'Arrays have a reverse() method',
'You can join an array back to a string using join()'
],
starterCode: `function reverseString(str) {
// Write your code here
}`,
solution: `function reverseString(str) {
return str.split('').reverse().join('');
}`,
tests: [
{
name: 'Reverses simple string',
test: () => {
try {
const result = reverseString("hello");
return {
pass: result === "olleh",
message: result === "olleh" ? 'Correct!' : `Expected "olleh" but got "${result}"`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Reverses complex string',
test: () => {
try {
const result = reverseString("JavaScript");
return {
pass: result === "tpircSavaJ",
message: result === "tpircSavaJ" ? 'Correct!' : `Expected "tpircSavaJ" but got "${result}"`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles empty string',
test: () => {
try {
const result = reverseString("");
return {
pass: result === "",
message: result === "" ? 'Correct!' : `Expected "" but got "${result}"`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
},
{
id: 'find-max',
title: 'Find Maximum in Array',
difficulty: 'medium',
category: 'Arrays',
description: 'Write a function that finds the maximum number in an array of numbers.',
examples: [
{ input: 'findMax([1, 3, 2])', output: '3' },
{ input: 'findMax([10, 5, 8, 20, 3])', output: '20' },
{ input: 'findMax([-1, -5, -2])', output: '-1' }
],
hints: [
'You can use Math.max() with the spread operator',
'Or use a loop to compare each element',
'Consider using reduce() method'
],
starterCode: `function findMax(numbers) {
// Write your code here
}`,
solution: `function findMax(numbers) {
return Math.max(...numbers);
}`,
tests: [
{
name: 'Finds max in positive numbers',
test: () => {
try {
const result = findMax([1, 3, 2]);
return {
pass: result === 3,
message: result === 3 ? 'Correct!' : `Expected 3 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Finds max in larger array',
test: () => {
try {
const result = findMax([10, 5, 8, 20, 3]);
return {
pass: result === 20,
message: result === 20 ? 'Correct!' : `Expected 20 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles negative numbers',
test: () => {
try {
const result = findMax([-1, -5, -2]);
return {
pass: result === -1,
message: result === -1 ? 'Correct!' : `Expected -1 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
},
{
id: 'count-vowels',
title: 'Count Vowels',
difficulty: 'medium',
category: 'String Manipulation',
description: 'Write a function that counts the number of vowels (a, e, i, o, u) in a string. Case should be ignored.',
examples: [
{ input: 'countVowels("hello")', output: '2' },
{ input: 'countVowels("JavaScript")', output: '3' },
{ input: 'countVowels("xyz")', output: '0' }
],
hints: [
'Convert the string to lowercase first',
'You can use a loop or filter method',
'Check if each character is in the vowels set'
],
starterCode: `function countVowels(str) {
// Write your code here
}`,
solution: `function countVowels(str) {
const vowels = 'aeiou';
return str.toLowerCase().split('').filter(char => vowels.includes(char)).length;
}`,
tests: [
{
name: 'Counts vowels correctly',
test: () => {
try {
const result = countVowels("hello");
return {
pass: result === 2,
message: result === 2 ? 'Correct!' : `Expected 2 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles mixed case',
test: () => {
try {
const result = countVowels("JavaScript");
return {
pass: result === 3,
message: result === 3 ? 'Correct!' : `Expected 3 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles no vowels',
test: () => {
try {
const result = countVowels("xyz");
return {
pass: result === 0,
message: result === 0 ? 'Correct!' : `Expected 0 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
},
{
id: 'factorial',
title: 'Calculate Factorial',
difficulty: 'hard',
category: 'Recursion',
description: 'Write a function that calculates the factorial of a positive integer. Factorial of n (n!) is the product of all positive integers less than or equal to n.',
examples: [
{ input: 'factorial(5)', output: '120' },
{ input: 'factorial(0)', output: '1' },
{ input: 'factorial(1)', output: '1' }
],
hints: [
'Factorial of 0 is 1 by definition',
'You can use recursion or iteration',
'n! = n × (n-1)!'
],
starterCode: `function factorial(n) {
// Write your code here
}`,
solution: `function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}`,
tests: [
{
name: 'Calculates 5!',
test: () => {
try {
const result = factorial(5);
return {
pass: result === 120,
message: result === 120 ? 'Correct!' : `Expected 120 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles base case 0',
test: () => {
try {
const result = factorial(0);
return {
pass: result === 1,
message: result === 1 ? 'Correct!' : `Expected 1 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles base case 1',
test: () => {
try {
const result = factorial(1);
return {
pass: result === 1,
message: result === 1 ? 'Correct!' : `Expected 1 but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
},
{
id: 'palindrome',
title: 'Check Palindrome',
difficulty: 'hard',
category: 'String Manipulation',
description: 'Write a function that checks if a string is a palindrome (reads the same forwards and backwards). Ignore spaces, punctuation, and case.',
examples: [
{ input: 'isPalindrome("racecar")', output: 'true' },
{ input: 'isPalindrome("A man a plan a canal Panama")', output: 'true' },
{ input: 'isPalindrome("hello")', output: 'false' }
],
hints: [
'Remove non-alphanumeric characters and convert to lowercase',
'Compare the string with its reverse',
'Use regular expressions to clean the string'
],
starterCode: `function isPalindrome(str) {
// Write your code here
}`,
solution: `function isPalindrome(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleaned === cleaned.split('').reverse().join('');
}`,
tests: [
{
name: 'Identifies simple palindrome',
test: () => {
try {
const result = isPalindrome("racecar");
return {
pass: result === true,
message: result === true ? 'Correct!' : `Expected true but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Handles complex palindrome',
test: () => {
try {
const result = isPalindrome("A man a plan a canal Panama");
return {
pass: result === true,
message: result === true ? 'Correct!' : `Expected true but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
},
{
name: 'Identifies non-palindrome',
test: () => {
try {
const result = isPalindrome("hello");
return {
pass: result === false,
message: result === false ? 'Correct!' : `Expected false but got ${result}`
};
} catch (e) {
return { pass: false, message: `Error: ${e.message}` };
}
}
}
],
completed: false
}
];
let currentExercise = null;
let currentFilter = 'all';
// Initialize the page
function init() {
renderExercises();
updateProgress();
loadProgress();
}
// Load progress from localStorage
function loadProgress() {
const saved = localStorage.getItem('js-exercises-progress');
if (saved) {
const progress = JSON.parse(saved);
exercises.forEach(exercise => {
if (progress[exercise.id]) {
exercise.completed = true;
}
});
renderExercises();
updateProgress();
}
}
// Save progress to localStorage
function saveProgress() {
const progress = {};
exercises.forEach(exercise => {
progress[exercise.id] = exercise.completed;
});
localStorage.setItem('js-exercises-progress', JSON.stringify(progress));
}
// Update progress bar
function updateProgress() {
const completed = exercises.filter(ex => ex.completed).length;
const total = exercises.length;
const percentage = (completed / total) * 100;
document.getElementById('progress-fill').style.width = percentage + '%';
document.getElementById('progress-text').textContent = `${completed} / ${total} completed`;
}
// Render exercises grid
function renderExercises() {
const grid = document.getElementById('exercises-grid');
const filtered = currentFilter === 'all' ? exercises : exercises.filter(ex => ex.difficulty === currentFilter);
grid.innerHTML = filtered.map(exercise => `
<div class="exercise-card bg-white rounded-lg shadow-md overflow-hidden ${exercise.completed ? 'ring-2 ring-green-400' : ''}"
onclick="openExercise('${exercise.id}')">
<div class="difficulty-${exercise.difficulty} p-4 text-white">
<div class="flex justify-between items-start">
<div>
<h3 class="font-bold text-lg">${exercise.title}</h3>
<p class="text-sm opacity-90 mt-1">${exercise.category}</p>
</div>
${exercise.completed ? '<div class="text-green-200">✅</div>' : ''}
</div>
</div>
<div class="p-6">
<p class="text-gray-600 mb-4">${exercise.description}</p>
<div class="flex justify-between items-center">
<span class="px-3 py-1 rounded-full text-xs font-medium ${getDifficultyClasses(exercise.difficulty)}">
${exercise.difficulty.charAt(0).toUpperCase() + exercise.difficulty.slice(1)}
</span>
<button class="text-edu-blue font-semibold hover:text-blue-600 transition-colors">
${exercise.completed ? 'Review →' : 'Start →'}
</button>
</div>
</div>
</div>
`).join('');
}
// Get difficulty badge classes
function getDifficultyClasses(difficulty) {
switch (difficulty) {
case 'easy': return 'bg-green-100 text-green-800';
case 'medium': return 'bg-yellow-100 text-yellow-800';
case 'hard': return 'bg-red-100 text-red-800';
default: return 'bg-gray-100 text-gray-800';
}
}
// Filter exercises
function filterExercises(filter) {
currentFilter = filter;
// Update active filter button
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.classList.remove('active', 'bg-edu-blue', 'text-white');
btn.classList.add('hover:bg-gray-50');
});
event.target.classList.add('active', 'bg-edu-blue', 'text-white');
event.target.classList.remove('hover:bg-gray-50');
renderExercises();
}
// Sort exercises
function sortExercises() {
const sortBy = document.getElementById('sort-select').value;
switch (sortBy) {
case 'difficulty':
exercises.sort((a, b) => {
const order = { easy: 1, medium: 2, hard: 3 };
return order[a.difficulty] - order[b.difficulty];
});
break;
case 'title':
exercises.sort((a, b) => a.title.localeCompare(b.title));
break;
case 'completed':
exercises.sort((a, b) => Number(a.completed) - Number(b.completed));
break;
default:
// Reset to original order
exercises.sort((a, b) => a.id.localeCompare(b.id));
}
renderExercises();
}
// Open exercise modal
function openExercise(exerciseId) {
currentExercise = exercises.find(ex => ex.id === exerciseId);
if (!currentExercise) return;
// Populate modal
document.getElementById('modal-title').textContent = currentExercise.title;
document.getElementById('modal-difficulty').textContent = currentExercise.difficulty.charAt(0).toUpperCase() + currentExercise.difficulty.slice(1);
document.getElementById('modal-difficulty').className = `px-3 py-1 rounded-full text-sm font-medium ${getDifficultyClasses(currentExercise.difficulty)}`;
document.getElementById('modal-category').textContent = currentExercise.category;
document.getElementById('modal-description').textContent = currentExercise.description;
// Populate examples
if (currentExercise.examples && currentExercise.examples.length > 0) {
const examplesContainer = document.getElementById('modal-examples');
examplesContainer.classList.remove('hidden');
examplesContainer.querySelector('.space-y-3').innerHTML = currentExercise.examples.map(example => `
<div class="bg-gray-50 p-3 rounded-lg">
<div class="text-sm font-mono">
<div><strong>Input:</strong> ${example.input}</div>
<div><strong>Output:</strong> ${example.output}</div>
</div>
</div>
`).join('');
}
// Set starter code
document.getElementById('code-editor').value = currentExercise.starterCode;
// Clear results
document.getElementById('test-results').innerHTML = '<div class="text-gray-500 text-sm">Run your code to see test results</div>';
document.getElementById('output-panel').textContent = 'Click "Run Tests" to see your code output and test results.';
// Show modal
document.getElementById('exercise-modal').classList.add('active');
}
// Close modal
function closeExercise() {
document.getElementById('exercise-modal').classList.remove('active');
currentExercise = null;
}