Repository navigation
Expand file tree
/
Copy pathtexts.js
More file actions
1425 lines (1421 loc) · 53.6 KB
/
Copy pathtexts.js
File metadata and controls
1425 lines (1421 loc) · 53.6 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
/**
* TypeSpeed text sources. Plain browser script, loaded before script.js,
* which reads COMMON_WORDS, QUOTES, and CODE_SNIPPETS.
*/
// --- Common Words ---
// Frequent English words. Runs in the Common Words category are drawn from
// this list at random.
const COMMON_WORDS = [
'the', 'be', 'of', 'and', 'a', 'to', 'in', 'he', 'have', 'it',
'that', 'for', 'they', 'with', 'as', 'not', 'on', 'she', 'at', 'by',
'this', 'we', 'you', 'do', 'but', 'from', 'or', 'which', 'one', 'would',
'all', 'will', 'there', 'say', 'who', 'make', 'when', 'can', 'more', 'if',
'no', 'man', 'out', 'other', 'so', 'what', 'time', 'up', 'go', 'about',
'than', 'into', 'could', 'state', 'only', 'new', 'year', 'some', 'take', 'come',
'these', 'know', 'see', 'use', 'get', 'like', 'then', 'first', 'any', 'work',
'now', 'may', 'such', 'give', 'over', 'think', 'most', 'even', 'find', 'day',
'also', 'after', 'way', 'many', 'must', 'look', 'before', 'great', 'back', 'through',
'long', 'where', 'much', 'should', 'well', 'people', 'down', 'own', 'just', 'because',
'good', 'each', 'those', 'feel', 'seem', 'how', 'high', 'too', 'place', 'little',
'world', 'very', 'still', 'nation', 'hand', 'old', 'life', 'tell', 'write', 'become',
'here', 'show', 'house', 'both', 'between', 'need', 'mean', 'call', 'develop', 'under',
'last', 'right', 'move', 'thing', 'general', 'school', 'never', 'same', 'another', 'begin',
'while', 'number', 'part', 'turn', 'real', 'leave', 'might', 'want', 'point', 'form',
'off', 'child', 'few', 'small', 'since', 'against', 'ask', 'late', 'home', 'interest',
'large', 'person', 'end', 'open', 'public', 'follow', 'during', 'present', 'without', 'again',
'hold', 'govern', 'around', 'possible', 'head', 'consider', 'word', 'program', 'problem', 'however',
'lead', 'system', 'set', 'order', 'eye', 'plan', 'run', 'keep', 'face', 'fact',
'group', 'play', 'stand', 'increase', 'early', 'course', 'change', 'help', 'line', 'city',
]; // prettier-ignore
// --- Lessons ---
// Words typed with only the home row (a s d f g h j k l), for the first
// lesson stage, where few common words fit.
const LESSON_HOME_WORDS = [
'a', 'as', 'ask', 'all', 'add', 'ads', 'dad', 'had', 'has', 'sad',
'lad', 'fad', 'gas', 'hall', 'fall', 'glad', 'flag', 'half', 'dash', 'gash',
'lash', 'sash', 'salad', 'shall', 'flask', 'alas', 'gala', 'jag', 'lag', 'hag',
'slag', 'flash', 'salsa', 'alfalfa', 'fads', 'lads', 'gags', 'hash',
]; // prettier-ignore
// --- Quotes ---
// Category name to passages. `source` is shown after a run and is left
// empty when the attribution could not be confirmed. Book passages are from
// works in the public domain.
const QUOTES = {
general: [
{ text: 'The quick brown fox jumps over the lazy dog.', source: '' },
{
text: 'Productivity is never an accident. It is always the result of a commitment to excellence, intelligent planning, and focused effort.',
source: '',
},
{
text: 'To be or not to be, that is the question.',
source: 'William Shakespeare, Hamlet',
},
{
text: 'This above all: to thine own self be true.',
source: 'William Shakespeare, Hamlet',
},
{
text: 'All our dreams can come true, if we have the courage to pursue them.',
source: '',
},
{ text: 'It does not matter how slowly you go as long as you do not stop.', source: '' },
{
text: 'Success is not final, failure is not fatal: it is the courage to continue that counts.',
source: '',
},
{ text: "Believe you can and you're halfway there.", source: '' },
{
text: 'The only way to do great work is to love what you do.',
source: 'Steve Jobs, Stanford commencement address, 2005',
},
{ text: 'In the middle of every difficulty lies opportunity.', source: '' },
{
text: 'Happiness is not something ready made. It comes from your own actions.',
source: '',
},
{
text: 'It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness.',
source: 'Charles Dickens, A Tale of Two Cities',
},
{
text: 'It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.',
source: 'Jane Austen, Pride and Prejudice',
},
{
text: 'Happy families are all alike; every unhappy family is unhappy in its own way.',
source: 'Leo Tolstoy, Anna Karenina',
},
{
text: 'Call me Ishmael. Some years ago, never mind how long precisely, having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.',
source: 'Herman Melville, Moby-Dick',
},
{
text: "In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.",
source: 'F. Scott Fitzgerald, The Great Gatsby',
},
{
text: 'Whether I shall turn out to be the hero of my own life, or whether that station will be held by anybody else, these pages must show.',
source: 'Charles Dickens, David Copperfield',
},
{
text: 'There was no possibility of taking a walk that day.',
source: 'Charlotte Bronte, Jane Eyre',
},
{
text: 'Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do.',
source: "Lewis Carroll, Alice's Adventures in Wonderland",
},
{
text: 'Marley was dead: to begin with. There is no doubt whatever about that.',
source: 'Charles Dickens, A Christmas Carol',
},
{
text: "You don't know about me without you have read a book by the name of The Adventures of Tom Sawyer; but that ain't no matter.",
source: 'Mark Twain, Adventures of Huckleberry Finn',
},
{
text: 'Stately, plump Buck Mulligan came from the stairhead, bearing a bowl of lather on which a mirror and a razor lay crossed.',
source: 'James Joyce, Ulysses',
},
{
text: 'Mrs. Dalloway said she would buy the flowers herself.',
source: 'Virginia Woolf, Mrs Dalloway',
},
{
text: 'Emma Woodhouse, handsome, clever, and rich, with a comfortable home and happy disposition, seemed to unite some of the best blessings of existence.',
source: 'Jane Austen, Emma',
},
{
text: 'Robert Cohn was once middleweight boxing champion of Princeton.',
source: 'Ernest Hemingway, The Sun Also Rises',
},
{
text: 'In the late summer of that year we lived in a house in a village that looked across the river and the plain to the mountains.',
source: 'Ernest Hemingway, A Farewell to Arms',
},
{
text: 'To Sherlock Holmes she is always the woman.',
source: 'Arthur Conan Doyle, A Scandal in Bohemia',
},
{
text: 'Mr. Sherlock Holmes, who was usually very late in the mornings, save upon those not infrequent occasions when he was up all night, was seated at the breakfast table.',
source: 'Arthur Conan Doyle, The Hound of the Baskervilles',
},
{
text: 'The studio was filled with the rich odour of roses, and when the light summer wind stirred amidst the trees of the garden, there came through the open door the heavy scent of the lilac.',
source: 'Oscar Wilde, The Picture of Dorian Gray',
},
{
text: 'I have just returned from a visit to my landlord, the solitary neighbour that I shall be troubled with.',
source: 'Emily Bronte, Wuthering Heights',
},
{
text: 'You will rejoice to hear that no disaster has accompanied the commencement of an enterprise which you have regarded with such evil forebodings.',
source: 'Mary Shelley, Frankenstein',
},
{
text: 'Ours is essentially a tragic age, so we refuse to take it tragically.',
source: "D. H. Lawrence, Lady Chatterley's Lover",
},
{
text: 'Now, what I want is, Facts. Teach these boys and girls nothing but Facts. Facts alone are wanted in life.',
source: 'Charles Dickens, Hard Times',
},
{
text: 'I had the story, bit by bit, from various people, and, as generally happens in such cases, each time it was a different story.',
source: 'Edith Wharton, Ethan Frome',
},
{
text: 'The cold passed reluctantly from the earth, and the retiring fogs revealed an army stretched out on the hills, resting.',
source: 'Stephen Crane, The Red Badge of Courage',
},
{
text: "No one would have believed in the last years of the nineteenth century that this world was being watched keenly and closely by intelligences greater than man's.",
source: 'H. G. Wells, The War of the Worlds',
},
{
text: 'The Time Traveller (for so it will be convenient to speak of him) was expounding a recondite matter to us.',
source: 'H. G. Wells, The Time Machine',
},
{
text: 'Buck did not read the newspapers, or he would have known that trouble was brewing, not alone for himself, but for every tide-water dog.',
source: 'Jack London, The Call of the Wild',
},
{ text: 'All children, except one, grow up.', source: 'J. M. Barrie, Peter and Wendy' },
{
text: "Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, who was a farmer, and Aunt Em, who was the farmer's wife.",
source: 'L. Frank Baum, The Wonderful Wizard of Oz',
},
{
text: '"Christmas won\'t be Christmas without any presents," grumbled Jo, lying on the rug.',
source: 'Louisa May Alcott, Little Women',
},
{
text: 'It was a dark and stormy night; the rain fell in torrents, except at occasional intervals, when it was checked by a violent gust of wind.',
source: 'Edward Bulwer-Lytton, Paul Clifford',
},
{
text: 'I went to the woods because I wished to live deliberately, to front only the essential facts of life, and see if I could not learn what it had to teach.',
source: 'Henry David Thoreau, Walden',
},
{
text: 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.',
source: 'Abraham Lincoln, Gettysburg Address',
},
{
text: "All the world's a stage, and all the men and women merely players.",
source: 'William Shakespeare, As You Like It',
},
{
text: 'Some are born great, some achieve greatness, and some have greatness thrust upon them.',
source: 'William Shakespeare, Twelfth Night',
},
{
text: 'The fault, dear Brutus, is not in our stars, but in ourselves, that we are underlings.',
source: 'William Shakespeare, Julius Caesar',
},
{
text: 'We are such stuff as dreams are made on, and our little life is rounded with a sleep.',
source: 'William Shakespeare, The Tempest',
},
{
text: 'A foolish consistency is the hobgoblin of little minds.',
source: 'Ralph Waldo Emerson, Self-Reliance',
},
{
text: 'Squire Trelawney, Dr. Livesey, and the rest of these gentlemen having asked me to write down the whole particulars about Treasure Island, from the beginning to the end.',
source: 'Robert Louis Stevenson, Treasure Island',
},
],
technology: [
{
text: 'Any sufficiently advanced technology is indistinguishable from magic.',
source: 'Arthur C. Clarke',
},
{ text: 'The science of today is the technology of tomorrow.', source: '' },
{ text: 'Technology is best when it brings people together.', source: '' },
{
text: 'It has become appallingly obvious that our technology has exceeded our humanity.',
source: '',
},
{ text: 'The Web does not just connect machines, it connects people.', source: '' },
{ text: 'Innovation distinguishes between a leader and a follower.', source: '' },
{ text: 'First we build the tools, then they build us.', source: '' },
{ text: "Code is like humor. When you have to explain it, it's bad.", source: '' },
{ text: 'Simplicity is the soul of efficiency.', source: '' },
{ text: 'Make it work, make it right, make it fast.', source: '' },
{
text: 'Premature optimization is the root of all evil.',
source: 'Donald Knuth, Structured Programming with go to Statements',
},
{
text: 'Programs must be written for people to read, and only incidentally for machines to execute.',
source: 'Abelson and Sussman, Structure and Interpretation of Computer Programs',
},
{ text: 'Talk is cheap. Show me the code.', source: 'Linus Torvalds' },
{ text: 'Simplicity is prerequisite for reliability.', source: 'Edsger W. Dijkstra' },
{
text: 'Controlling complexity is the essence of computer programming.',
source: 'Brian Kernighan',
},
{
text: 'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.',
source: 'Brian Kernighan',
},
{
text: 'Walking on water and developing software from a specification are easy if both are frozen.',
source: 'Edward V. Berard',
},
{ text: 'The best way to predict the future is to invent it.', source: 'Alan Kay' },
{
text: 'Adding manpower to a late software project makes it later.',
source: 'Fred Brooks, The Mythical Man-Month',
},
{
text: 'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
source: 'Martin Fowler, Refactoring',
},
{
text: 'Testing shows the presence, not the absence of bugs.',
source: 'Edsger W. Dijkstra',
},
{
text: 'Beware of bugs in the above code; I have only proved it correct, not tried it.',
source: 'Donald Knuth',
},
{
text: 'Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.',
source: 'Antoine de Saint-Exupery, Wind, Sand and Stars',
},
{
text: "Rule 1: Don't do it. Rule 2, for experts only: Don't do it yet.",
source: 'Michael A. Jackson',
},
{
text: "A language that doesn't affect the way you think about programming is not worth knowing.",
source: 'Alan Perlis, Epigrams on Programming',
},
{
text: 'Simplicity does not precede complexity, but follows it.',
source: 'Alan Perlis, Epigrams on Programming',
},
{
text: 'Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it.',
source: 'Alan Perlis, Epigrams on Programming',
},
{
text: 'There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.',
source: "C. A. R. Hoare, The Emperor's Old Clothes",
},
{ text: 'When in doubt, use brute force.', source: 'Ken Thompson' },
{
text: 'Software is like entropy: it is difficult to grasp, weighs nothing, and obeys the second law of thermodynamics; i.e., it always increases.',
source: "Norman Augustine, Augustine's Laws",
},
{ text: 'Real artists ship.', source: 'Steve Jobs' },
{
text: 'Science is what we understand well enough to explain to a computer. Art is everything else we do.',
source: 'Donald Knuth',
},
{
text: 'The purpose of computing is insight, not numbers.',
source: 'Richard Hamming, Numerical Methods for Scientists and Engineers',
},
{
text: 'Given enough eyeballs, all bugs are shallow.',
source: 'Eric S. Raymond, The Cathedral and the Bazaar',
},
{
text: 'Plan to throw one away; you will, anyhow.',
source: 'Fred Brooks, The Mythical Man-Month',
},
{
text: 'The bearing of a child takes nine months, no matter how many women are assigned.',
source: 'Fred Brooks, The Mythical Man-Month',
},
{
text: 'Bad programmers worry about the code. Good programmers worry about data structures and their relationships.',
source: 'Linus Torvalds',
},
{
text: 'Optimism is an occupational hazard of programming; feedback is the treatment.',
source: 'Kent Beck, Extreme Programming Explained',
},
{
text: 'The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.',
source: 'Edsger W. Dijkstra',
},
{
text: 'Computers are good at following instructions, but not at reading your mind.',
source: 'Donald Knuth, The TeXbook',
},
{
text: 'Lisp is worth learning for the profound enlightenment experience you will have when you finally get it.',
source: 'Eric S. Raymond, How To Become A Hacker',
},
{ text: 'Weeks of coding can save you hours of planning.', source: '' },
{ text: "It's not a bug, it's a feature.", source: '' },
{
text: 'There are only two hard things in computer science: cache invalidation and naming things.',
source: 'Phil Karlton',
},
{
text: 'Good code is its own best documentation.',
source: 'Steve McConnell, Code Complete',
},
{
text: 'One of my most productive days was throwing away 1000 lines of code.',
source: 'Ken Thompson',
},
{
text: "Show me your tables, and I won't usually need your flowcharts; they'll be obvious.",
source: 'Fred Brooks, The Mythical Man-Month',
},
{
text: 'A program that produces incorrect results twice as fast is infinitely slower.',
source: '',
},
{
text: 'Measuring programming progress by lines of code is like measuring aircraft building progress by weight.',
source: '',
},
{ text: 'Deleted code is debugged code.', source: '' },
],
};
// --- Code Snippets ---
// Language name to multi-line snippets for the Code Snippets category.
// Indentation is spaces; lines are joined with \n.
const CODE_SNIPPETS = {
javascript: [
[
'function debounce(fn, wait) {',
' let timer;',
' return (...args) => {',
' clearTimeout(timer);',
' timer = setTimeout(() => fn(...args), wait);',
' };',
'}',
],
[
'const counts = {};',
'for (const word of text.split(/\\s+/)) {',
' counts[word] = (counts[word] || 0) + 1;',
'}',
],
[
'async function loadUser(id) {',
' const response = await fetch(`/api/users/${id}`);',
' if (!response.ok) throw new Error(response.statusText);',
' return response.json();',
'}',
],
[
'const total = items',
' .filter((item) => item.inStock)',
' .map((item) => item.price * item.quantity)',
' .reduce((sum, value) => sum + value, 0);',
],
[
'class Stack {',
' #items = [];',
' push(item) {',
' this.#items.push(item);',
' }',
' pop() {',
' return this.#items.pop();',
' }',
'}',
],
[
"document.querySelector('#save').addEventListener('click', (event) => {",
' event.preventDefault();',
" localStorage.setItem('draft', editor.value);",
'});',
],
[
'function groupBy(list, keyFn) {',
' return list.reduce((groups, item) => {',
' const key = keyFn(item);',
' (groups[key] ??= []).push(item);',
' return groups;',
' }, {});',
'}',
],
[
'const params = new URLSearchParams(location.search);',
"const page = Number(params.get('page') ?? 1);",
"const query = params.get('q')?.trim() || '';",
],
[
'class Emitter extends EventTarget {',
' emit(name, detail) {',
' this.dispatchEvent(new CustomEvent(name, { detail }));',
' }',
'}',
'const bus = new Emitter();',
"bus.addEventListener('save', (e) => console.log(e.detail));",
],
[
'async function retry(task, attempts = 3) {',
' try {',
' return await task();',
' } catch (err) {',
' if (attempts <= 1) throw err;',
' return retry(task, attempts - 1);',
' }',
'}',
],
[
'const unique = [...new Set(tags.map((t) => t.toLowerCase()))];',
'unique.sort((a, b) => a.localeCompare(b));',
"console.log(unique.join(', '));",
],
[
'const { name, age = 0, ...rest } = user;',
'const copy = { ...rest, name: name.toUpperCase(), age: age + 1 };',
'Object.freeze(copy);',
],
[
"const formatter = new Intl.NumberFormat('en-US', {",
" style: 'currency',",
" currency: 'USD',",
'});',
'const label = formatter.format(cents / 100);',
],
[
'function clamp(value, min, max) {',
' return Math.min(Math.max(value, min), max);',
'}',
'const percent = clamp(Math.round((done / total) * 100), 0, 100);',
],
[
"const res = await fetch('/api/items', {",
" method: 'POST',",
" headers: { 'Content-Type': 'application/json' },",
' body: JSON.stringify({ title, done: false }),',
'});',
],
[
'const timer = setInterval(() => {',
' remaining -= 1;',
' label.textContent = `${remaining}s left`;',
' if (remaining <= 0) clearInterval(timer);',
'}, 1000);',
],
[
'function slugify(title) {',
' return title',
' .toLowerCase()',
" .replace(/[^a-z0-9]+/g, '-')",
" .replace(/^-|-$/g, '');",
'}',
],
[
'const observer = new IntersectionObserver((entries) => {',
' for (const entry of entries) {',
" entry.target.classList.toggle('visible', entry.isIntersecting);",
' }',
'});',
'cards.forEach((card) => observer.observe(card));',
],
[
'const [first, second, ...others] = scores.toSorted((a, b) => b - a);',
'const podium = { gold: first, silver: second };',
'console.log(podium, `and ${others.length} more`);',
],
[
'switch (event.key) {',
" case 'ArrowUp':",
' index = Math.max(0, index - 1);',
' break;',
" case 'ArrowDown':",
' index = Math.min(items.length - 1, index + 1);',
' break;',
'}',
],
[
'function memoize(fn) {',
' const cache = new Map();',
' return (arg) => {',
' if (!cache.has(arg)) cache.set(arg, fn(arg));',
' return cache.get(arg);',
' };',
'}',
],
[
'const results = await Promise.allSettled(urls.map((u) => fetch(u)));',
'const failed = results',
" .filter((r) => r.status === 'rejected')",
' .map((r) => r.reason.message);',
],
[
'const isEmail = (value) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value);',
'if (!isEmail(input.value)) {',
" input.setCustomValidity('Enter a valid email address');",
'}',
],
[
'const lines = Object.entries(prices)',
' .filter(([, price]) => price > 0)',
' .map(([sku, price]) => `${sku}: $${price.toFixed(2)}`);',
],
[
'const controller = new AbortController();',
'const timeout = setTimeout(() => controller.abort(), 5000);',
'const data = await fetch(url, { signal: controller.signal });',
'clearTimeout(timeout);',
],
[
'class Temperature {',
' constructor(celsius) {',
' this.celsius = celsius;',
' }',
' get fahrenheit() {',
' return (this.celsius * 9) / 5 + 32;',
' }',
'}',
],
],
python: [
[
'def fibonacci(n):',
' a, b = 0, 1',
' for _ in range(n):',
' a, b = b, a + b',
' return a',
],
[
'with open("data.csv", newline="") as handle:',
' for row in csv.DictReader(handle):',
' print(row["name"], row["email"])',
],
[
'class Point:',
' def __init__(self, x, y):',
' self.x = x',
' self.y = y',
'',
' def __repr__(self):',
' return f"Point({self.x}, {self.y})"',
],
[
'squares = {n: n * n for n in range(10) if n % 2 == 0}',
'for key, value in sorted(squares.items()):',
' print(f"{key}: {value}")',
],
[
'try:',
' port = int(os.environ.get("PORT", "8000"))',
'except ValueError:',
' port = 8000',
],
[
'def read_lines(path):',
' with open(path) as handle:',
' for line in handle:',
' yield line.rstrip("\\n")',
],
[
'from collections import Counter',
'',
'words = text.lower().split()',
'for word, count in Counter(words).most_common(5):',
' print(f"{word:<12} {count:>4}")',
],
[
'@dataclass',
'class Item:',
' name: str',
' price: float',
' tags: list[str] = field(default_factory=list)',
],
[
'def chunked(items, size):',
' for i in range(0, len(items), size):',
' yield items[i : i + size]',
],
[
'def timed(func):',
' @functools.wraps(func)',
' def wrapper(*args, **kwargs):',
' start = time.perf_counter()',
' result = func(*args, **kwargs)',
' print(f"{func.__name__}: {time.perf_counter() - start:.3f}s")',
' return result',
' return wrapper',
],
[
'path = Path("logs") / "app.log"',
'path.parent.mkdir(parents=True, exist_ok=True)',
'path.write_text("started\\n", encoding="utf-8")',
],
[
'with open("config.json") as f:',
' config = json.load(f)',
'debug = config.get("debug", False)',
'hosts = [h.strip() for h in config["hosts"] if h]',
],
[
'class BankAccount:',
' def __init__(self, balance=0):',
' self._balance = balance',
'',
' def withdraw(self, amount):',
' if amount > self._balance:',
' raise ValueError("insufficient funds")',
' self._balance -= amount',
],
[
'users.sort(key=lambda u: (u["last"], u["first"]))',
'by_id = {u["id"]: u for u in users}',
'admins = [u for u in users if u.get("role") == "admin"]',
],
[
'match command.split():',
' case ["go", direction]:',
' move(direction)',
' case ["take", *items]:',
' pick_up(items)',
' case _:',
' print("unknown command")',
],
[
'def contains(sorted_values, target):',
' i = bisect.bisect_left(sorted_values, target)',
' return i < len(sorted_values) and sorted_values[i] == target',
],
[
'async def fetch_all(session, urls):',
' tasks = [session.get(url) for url in urls]',
' responses = await asyncio.gather(*tasks, return_exceptions=True)',
' return [r for r in responses if not isinstance(r, Exception)]',
],
[
'parser = argparse.ArgumentParser(description="Resize images")',
'parser.add_argument("paths", nargs="+")',
'parser.add_argument("--width", type=int, default=800)',
'args = parser.parse_args()',
],
[
'class Stack:',
' def __init__(self):',
' self._items = []',
'',
' def __len__(self):',
' return len(self._items)',
],
[
'pattern = re.compile(r"(\\d{4})-(\\d{2})-(\\d{2})")',
'for year, month, day in pattern.findall(log):',
' print(f"{day}/{month}/{year}")',
],
[
'@contextmanager',
'def cd(path):',
' previous = os.getcwd()',
' os.chdir(path)',
' try:',
' yield',
' finally:',
' os.chdir(previous)',
],
[
'totals = defaultdict(int)',
'for order in orders:',
' totals[order.customer] += order.amount',
'top = max(totals, key=totals.get)',
],
[
'def flatten(nested):',
' for item in nested:',
' if isinstance(item, (list, tuple)):',
' yield from flatten(item)',
' else:',
' yield item',
],
[
'try:',
' response = requests.get(url, timeout=10)',
' response.raise_for_status()',
'except requests.RequestException as exc:',
' logging.error("request failed: %s", exc)',
' raise SystemExit(1)',
],
[
'class Vector(NamedTuple):',
' x: float',
' y: float',
'',
' def __add__(self, other):',
' return Vector(self.x + other.x, self.y + other.y)',
],
[
'pairs = list(zip(names, scores))',
'passed = {name for name, score in pairs if score >= 50}',
'print(", ".join(sorted(passed)) or "nobody passed")',
],
['import sys', '', 'if __name__ == "__main__":', ' sys.exit(main(sys.argv[1:]))'],
],
go: [
[
'func sum(values []int) int {',
' total := 0',
' for _, v := range values {',
' total += v',
' }',
' return total',
'}',
],
[
'file, err := os.Open(path)',
'if err != nil {',
' return err',
'}',
'defer file.Close()',
],
[
'type User struct {',
' ID int `json:"id"`',
' Name string `json:"name"`',
' Email string `json:"email"`',
'}',
],
[
'http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {',
' w.WriteHeader(http.StatusOK)',
' fmt.Fprintln(w, "ok")',
'})',
],
[
'results := make(chan int)',
'go func() {',
' defer close(results)',
' for i := 0; i < 3; i++ {',
' results <- i * i',
' }',
'}()',
],
[
'switch day {',
'case "Saturday", "Sunday":',
' fmt.Println("weekend")',
'default:',
' fmt.Println("weekday")',
'}',
],
['type Shape interface {', ' Area() float64', ' Perimeter() float64', '}'],
['func (r Rect) Area() float64 {', ' return r.Width * r.Height', '}'],
[
'func reverse(s string) string {',
' runes := []rune(s)',
' for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {',
' runes[i], runes[j] = runes[j], runes[i]',
' }',
' return string(runes)',
'}',
],
[
'counts := make(map[string]int)',
'for _, word := range strings.Fields(text) {',
' counts[strings.ToLower(word)]++',
'}',
],
[
'var wg sync.WaitGroup',
'for _, url := range urls {',
' wg.Add(1)',
' go func(u string) {',
' defer wg.Done()',
' fetch(u)',
' }(url)',
'}',
],
[
'if err := json.NewDecoder(r.Body).Decode(&req); err != nil {',
' http.Error(w, "invalid JSON", http.StatusBadRequest)',
' return',
'}',
],
[
'var ErrNotFound = errors.New("not found")',
'',
'if errors.Is(err, ErrNotFound) {',
' return nil, fmt.Errorf("user %d: %w", id, err)',
'}',
],
[
'select {',
'case msg := <-messages:',
' fmt.Println("received", msg)',
'case <-time.After(2 * time.Second):',
' fmt.Println("timeout")',
'}',
],
[
'sort.Slice(people, func(i, j int) bool {',
' return people[i].Age < people[j].Age',
'})',
],
[
'ctx, cancel := context.WithTimeout(ctx, 5*time.Second)',
'defer cancel()',
'req, err := http.NewRequestWithContext(ctx, "GET", url, nil)',
],
[
'scanner := bufio.NewScanner(os.Stdin)',
'for scanner.Scan() {',
' line := strings.TrimSpace(scanner.Text())',
' if line == "" {',
' continue',
' }',
' fmt.Println(len(line), line)',
'}',
],
[
'func Map[T, U any](items []T, fn func(T) U) []U {',
' out := make([]U, 0, len(items))',
' for _, item := range items {',
' out = append(out, fn(item))',
' }',
' return out',
'}',
],
[
'func (c *Counter) Inc() {',
' c.mu.Lock()',
' defer c.mu.Unlock()',
' c.value++',
'}',
],
['func (p Point) String() string {', ' return fmt.Sprintf("(%d, %d)", p.X, p.Y)', '}'],
[
'data, err := os.ReadFile("config.yaml")',
'if err != nil {',
' log.Fatalf("read config: %v", err)',
'}',
'lines := strings.Split(string(data), "\\n")',
],
['const (', ' Low Priority = iota', ' Medium', ' High', ')'],
[
'jobs := make(chan int, 100)',
'for w := 1; w <= 3; w++ {',
' go func(id int) {',
' for j := range jobs {',
' fmt.Printf("worker %d: job %d\\n", id, j)',
' }',
' }(w)',
'}',
],
[
'if v, ok := cache[key]; ok {',
' return v, nil',
'}',
'v, err := load(key)',
'cache[key] = v',
'return v, err',
],
[
'n, err := strconv.Atoi(r.URL.Query().Get("limit"))',
'if err != nil || n < 1 {',
' n = 20',
'}',
],
[
'var b strings.Builder',
'for i, name := range names {',
' if i > 0 {',
' b.WriteString(", ")',
' }',
' b.WriteString(name)',
'}',
],
[
'defer func() {',
' if r := recover(); r != nil {',
' log.Printf("recovered: %v", r)',
' }',
'}()',
],
],
rust: [
[
'fn largest(values: &[i32]) -> Option<i32> {',
' let mut iter = values.iter();',
' let first = *iter.next()?;',
' Some(iter.fold(first, |max, &v| max.max(v)))',
'}',
],
['#[derive(Debug, Clone, PartialEq)]', 'struct Point {', ' x: f64,', ' y: f64,', '}'],
[
'match command.as_str() {',
' "start" => server.start(),',
' "stop" => server.stop(),',
' other => eprintln!("unknown command: {other}"),',
'}',
],
[
'let words: Vec<&str> = text',
' .split_whitespace()',
' .filter(|w| w.len() > 3)',
' .collect();',
],
[
'impl Drop for Connection {',
' fn drop(&mut self) {',
' println!("closing {}", self.address);',
' }',
'}',
],
[
'fn read_config(path: &str) -> std::io::Result<String> {',
' let contents = std::fs::read_to_string(path)?;',
' Ok(contents.trim().to_string())',
'}',
],
[
'trait Shape {',
' fn area(&self) -> f64;',
' fn name(&self) -> String {',
' String::from("shape")',
' }',
'}',
],
[
'impl Shape for Circle {',
' fn area(&self) -> f64 {',
' std::f64::consts::PI * self.radius * self.radius',
' }',
'}',
],
[
'let mut counts: HashMap<&str, usize> = HashMap::new();',
'for word in text.split_whitespace() {',
' *counts.entry(word).or_insert(0) += 1;',
'}',
],