forked from jamiebuilds/itsy-bitsy-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
itsy-bitsy-data-structures.js
1462 lines (1308 loc) · 62.1 KB
/
itsy-bitsy-data-structures.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
'use strict';
/**
* ███████████████═╗ ███████████████═╗ █████████████═╗ █████═╗ █████═╗
* ███████████████ ║ ███████████████ ║ ███████████████ ║ █████ ║ █████ ║
* ╚═══█████ ╔════╝ ╚═══█████ ╔════╝ █████ ╔═════════╝ █████ ║ █████ ║
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* █████ ║ █████ ║ █████████████═╗ ███████████████ ║
* █████ ║ █████ ║ ╚█████████████═╗ ╚███████████ ╔═╝
* █████ ║ █████ ║ ╚══════█████ ║ ╚═█████ ╔══╝
* █████ ║ █████ ║ █████ ║ █████ ║
* ███████████████═╗ █████ ║ ███████████████ ║ █████ ║
* ███████████████ ║ █████ ║ █████████████ ╔═╝ █████ ║
* ╚══════════════╝ ╚════╝ ╚════════════╝ ╚════╝
*
* █████████████═══╗ ███████████████═╗ ███████████████═╗ █████████████═╗ █████═╗ █████═╗
* ███████████████ ║ ███████████████ ║ ███████████████ ║ ███████████████ ║ █████ ║ █████ ║
* █████ ╔═══█████ ║ ╚═══█████ ╔════╝ ╚═══█████ ╔════╝ █████ ╔═════════╝ █████ ║ █████ ║
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* █████████████ ╔═╝ █████ ║ █████ ║ █████████████═╗ ███████████████ ║
* ███████████████═╗ █████ ║ █████ ║ ╚█████████████═╗ ╚███████████ ╔═╝
* █████ ╔═══█████ ║ █████ ║ █████ ║ ╚══════█████ ║ ╚═█████ ╔══╝
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* ███████████████ ║ ███████████████═╗ █████ ║ ███████████████ ║ █████ ║
* █████████████ ╔═╝ ███████████████ ║ █████ ║ █████████████ ╔═╝ █████ ║
* ╚════════════╝ ╚══════════════╝ ╚════╝ ╚════════════╝ ╚════╝
*
* █████████████═══╗ ███████████═══╗ ███████████████═╗ ███████████═══╗
* ███████████████ ║ ███████████████ ║ ███████████████ ║ ███████████████ ║
* █████ ╔═══█████ ║ █████ ╔═══█████ ║ ╚═══█████ ╔════╝ █████ ╔═══█████ ║
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* █████ ║ █████ ║ ███████████████ ║ █████ ║ ███████████████ ║
* █████ ║ █████ ║ ███████████████ ║ █████ ║ ███████████████ ║
* █████ ║ █████ ║ █████ ╔═══█████ ║ █████ ║ █████ ╔═══█████ ║
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* ███████████████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* █████████████ ╔═╝ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* ╚════════════╝ ╚════╝ ╚════╝ ╚════╝ ╚════╝ ╚════╝
*
* █████████████═╗ ███████████████═╗ █████████████═══╗ █████═╗ █████═╗ █████████████═╗ ███████████████═╗
* ███████████████ ║ ███████████████ ║ ███████████████ ║ █████ ║ █████ ║ ███████████████ ║ ███████████████ ║
* █████ ╔═════════╝ ╚═══█████ ╔════╝ █████ ╔═══█████ ║ █████ ║ █████ ║ █████ ╔═════════╝ ╚═══█████ ╔════╝
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* █████████████═╗ █████ ║ █████████████ ╔═╝ █████ ║ █████ ║ █████ ║ █████ ║
* ╚█████████████═╗ █████ ║ ███████████████═╗ █████ ║ █████ ║ █████ ║ █████ ║
* ╚══════█████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* ███████████████ ║ █████ ║ █████ ║ █████ ║ ███████████████ ║ ███████████████═╗ █████ ║
* █████████████ ╔═╝ █████ ║ █████ ║ █████ ║ ╚███████████ ╔═╝ ╚█████████████ ║ █████ ║
* ╚════════════╝ ╚════╝ ╚════╝ ╚════╝ ╚══════════╝ ╚════════════╝ ╚════╝
*
* █████═╗ █████═╗ █████████████═══╗ ████████████████═╗ ██████████████═╗
* █████ ║ █████ ║ ███████████████ ║ ████████████████ ║ ████████████████ ║
* █████ ║ █████ ║ █████ ╔═══█████ ║ █████ ╔══════════╝ █████ ╔══════════╝
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* █████ ║ █████ ║ █████████████ ╔═╝ ████████████████═╗ ██████████████═╗
* █████ ║ █████ ║ ███████████████═╗ ████████████████ ║ ╚██████████████═╗
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ╔══════════╝ ╚═══════█████ ║
* █████ ║ █████ ║ █████ ║ █████ ║ █████ ║ █████ ║
* ███████████████ ║ █████ ║ █████ ║ ████████████████═╗ ████████████████ ║
* ╚███████████ ╔═╝ █████ ║ █████ ║ ████████████████ ║ ██████████████ ╔═╝
* ╚══════════╝ ╚════╝ ╚════╝ ╚═══════════════╝ ╚═════════════╝
*
* ══════════════════════════════════════════════════════════════════════
* ████ By James Kyle (@thejameskyle) █████████████████████████████████████████
* ══════════════════════════════════════════════════════════════════════
*/
/**
* Today we're gonna learn all about data structures.
*
* "OOooooOOOooh *soo* exciting" right?
*
* Yeah, they definitely aren't the juiciest topic out there, but they are
* important. Not just to pass computer science 101, but in order to be a
* better programmer.
*
* Knowing your data structures can help you:
*
* - Manage complexity and make your programs easier to follow.
* - Build highly-performant, memory-efficient programs.
*
* The first of those is the one that I believe to be more important. Using the
* right data structure can drastically simplify what would otherwise be
* complicated logic.
*
* The second point is important too. If performance or memory matters then
* using the right data structure is more than often essential.
*
* In order to learn about data structures, we're going to implement a few of
* them together. Don't worry, we'll keep the code nice and short. In fact,
* there's way more comments than there is code.
*/
/**
* ============================================================================
* ,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'
* ============================================================================
*/
/**
* What are data structures?
*
* Essentially, they are different methods of storing and organizing data that
* serve a number of different needs.
*
* Data can always be represented in many different ways. However, depending on
* what that data is and what you need to do with it, one representation will
* be a better choice than the others.
*
* To understand why, let's first talk a bit about algorithms.
*/
/*** ===================================================================== ***\
** - ALGORITHMS ---------------------------------------------------------- **
* ========================================================================= *
* *
* ,--,--. ,--,--. *
* ,----------. | | | | | | _____ *
* |`----------'| | | | | | | | | ,------. *
* | | | | | | | | ,--. | o o | |`------'| *
* | | ,| +-|-+ | | +-|-+ |` | | |_____| | | *
* | | ,:==| | |###|======|###| | |====#==#====#=,, | | *
* | | || `| +---+ | | +---+ |' ,,=#==#====O=`` ,| | *
* | | || | | | | | | ``=#==#====#=====|| | *
* `----------' || | | | | | | |__| `| | *
* | | ``=| |===`` `--,',--` `--,',--` /||\ `------' *
** \_/ \_/ / / \ \ / / \ \ //||\\ |_| |_| **
\*** ===================================================================== ***/
/**
* Algorithms is a fancy name for step-by-step sets of operations to be
* performed.
*
* Data structures are implemented with algorithms, and algorithms are
* implemented with data structures. It's data structures and algorithms all
* the way down until you reach the micro-scopic people with punch cards that
* control the computer (Yeah– Intel is enslaving super tiny people. Wake up
* sheeple!)
*
* Any given task can be implemented in an infinite number of ways. So for
* common tasks there are often many different algorithms people have come up
* with.
*
* For example, there are an absurd number of algorithms for sorting a set of
* unordered items:
*
* Insertion Sort, Selection Sort, Merge Sort, Bubble Sort, Heap Sort,
* Quick Sort, Shell Sort, Timsort, Bucket Sort, Radix Sort, ...
*
* Some of these are significantly faster than others. Some use less memory.
* Some are easy to implement. Some are based on assumptions about the dataset.
*
* Every single one of them will be better for *something*. So you'll need to
* make a decision based on what your needs are and for that you'll need a way
* of comparing them, a way to measure them.
*
* When we compare the performance of algorithms we use a rough measurement of
* their average and worst-case performance using something called "Big-O".
*/
/*** ===================================================================== ***\
** - BIG-O NOTATION ------------------------------------------------------ **
* ========================================================================= *
* a b d *
* a b O(N^2) d *
* O(N!) a b O(N log N) d c *
* a b d c *
* a b d c O(N) *
* a b d c *
* a b d c *
* a b d c *
* ab c O(1) *
* e e e e ec d e e e e e e e e *
* ba c d *
* ba c d f f f f f f f *
** cadf f d f f f f f O(log N) **
\*** ===================================================================== ***/
/**
* Big-O Notation is a way of roughly measuring the performance of algorithms
* in order to compare one against another when discussing them.
*
* Big-O is a mathematical notation that we borrowed in computer science to
* classify algorithms by how they respond to the number (N) of items that you
* give them.
*
* There are two primary things that you measure with Big-O:
*
* - **Time complexity** refers to the total count of operations an algorithm
* will perform given a set of items.
*
* - **Space complexity** refers to the total memory an algorithm will take up
* while running given a set of items.
*
* We measure these independently from one another because while an algorithm
* may perform less operations than another it may also take up way more
* memory. Depending on what your requirements are one may be a better choice
* than the other.
*
* These are some common Big-O's:
*
* Name Notation How you feel when they show up at your party
* ------------------------------------------------------------------------
* Constant O(1) AWESOME!!
* Logarithmic O(log N) GREAT!
* Linear O(N) OKAY.
* Linearithmic O(N log N) UGH...
* Polynomial O(N ^ 2) SHITTY
* Exponential O(2 ^ N) HORRIBLE
* Factorial O(N!) WTF
*
* To give you an idea of how many operations we're talking about. Let's look
* at what these would equal given the (N) number of items.
*
* N = 5 10 20 30
* -----------------------------------------------------------------------
* O(1) 1 1 1 1
* O(log N) 1.6094... 2.3025... 2.9957... 3.4011...
* O(N) 5 10 20 30
* O(N log N) 8.0471... 23.0258... 59.9146... 102.0359...
* O(N ^ 2) 25 100 400 900
* O(2 ^ N) 32 1024 1,048,576 1,073,741,824
* O(N!) 120 3,628,800 2,432,902,0... 265,252,859,812,191,058,636,308,480,000,000
*
* As you can see, even for relatively small sets of data you could do a *lot*
* of extra work.
*
* With data structures, you have 4 primary types of actions you can perform:
* Accessing, Searching, Inserting, and Deleting.
*
* It is important to note that data structures may be good at one action but
* bad at another.
*
* Accessing Searching Inserting Deleting
* -------------------------------------------------------------------------
* Array O(1) O(N) O(N) O(N)
* Linked List O(N) O(N) O(1) O(1)
* Binary Search Tree O(log N) O(log N) O(log N) O(log N)
*
* Or rather...
*
* Accessing Searching Inserting Deleting
* -------------------------------------------------------------------------
* Array AWESOME!! OKAY OKAY OKAY
* Linked List OKAY OKAY AWESOME!! AWESOME!!
* Binary Search Tree GREAT! GREAT! GREAT! GREAT!
*
* Even further, some actions will have a different "average" performance and a
* "worst case scenario" performance.
*
* There is no perfect data structure, and you choose one over another based on
* the data that you are working with and the things you are going to do with
* it. This is why it is important to know a number of different common data
* structures so that you can choose from them.
*/
/*** ===================================================================== ***\
** - MEMORY -------------------------------------------------------------- **
* ========================================================================= *
* _.-.. *
* ,'9 )\)`-.,.--. *
* `-.| `. *
* \, , \) *
* `. )._\ (\ *
* |// `-,// *
* ]|| //" *
** hjw "" "" **
\*** ===================================================================== ***/
/**
* A computer's memory is pretty boring, it's just a bunch of ordered slots
* where you can store information. You hold onto memory addresses in order to
* find information.
*
* Lets imagine a chunk of memory like this:
*
* Values: |1001|0110|1000|0100|0101|1010|0010|0001|1101|1011...
* Addresses: 0 1 2 3 4 5 6 7 8 9 ...
*
* If you've ever wondered why things are zero-indexed in programming languages
* before it is because of the way that memory works. If you want to read the
* first chunk of memory you read from 0 to 1, the second you read from 1 to 2.
* So the address that you hold onto for each of those is 0 and 1 respectively.
*
* Your computer has much much more memory than this, and it is all just a
* continuation of the pattern above.
*
* Memory is a bit like the wild west, every program running on your machine is
* stored within this same *physical* data structure. Without layers of
* abstraction over it, it would be extremely difficult to use.
*
* But these abstractions serve two additional purposes:
*
* - Storing data in memory in a way that is more efficient and/or faster to
* work with.
* - Storing data in memory in a way that makes it easier to use.
*/
/*** ===================================================================== ***\
** - LISTS --------------------------------------------------------------- **
* ========================================================================= *
* * _______________________ *
* ()=(_______________________)=() * *
* * | | *
* | ~ ~~~~~~~~~~~~~ | * * *
* * | | *
* * | ~ ~~~~~~~~~~~~~ | * *
* | | *
* | ~ ~~~~~~~~~~~~~ | * *
* * | | *
* * |_____________________| * * *
* ()=(_______________________)=() *
** **
\*** ===================================================================== ***/
/**
* To demonstrate the raw interaction between memory and a data structure we're
* going to first implement a list.
*
* A list is a representation of an ordered sequence of values where the same
* value may appear many times.
*/
class List {
/**
* We start with an empty block of memory which we are going to represent
* with a normal JavaScript array and we'll store the length of the list.
*
* Note that we want to store the length separately because in real life the
* "memory" doesn't have a length you can read from.
*/
constructor() {
this.memory = [];
this.length = 0;
}
/**
* First we need a way to retrieve data from our list.
*
* With a plain list, you have very fast memory access because you keep track
* of the address directly.
*
* List access is constant O(1) - "AWESOME!!"
*/
get(address) {
return this.memory[address];
}
/**
* Because lists have an order you can insert stuff at the start, middle,
* or end of them.
*
* For our implementation we're going to focus on adding and removing values
* at the start or end of our list with these four methods:
*
* - Push - Add value to the end
* - Pop - Remove value from the end
* - Unshift - Add value to the start
* - Shift - Remove value from the start
*/
/*
* Starting with "push" we need a way to add items to the end of the list.
*
* It is as simple as adding a value in the address after the end of our
* list. Because we store the length this is easy to calculate. We just add
* the value and increment our length.
*
* Pushing an item to the end of a list is constant O(1) - "AWESOME!!"
*/
push(value) {
this.memory[this.length] = value;
this.length++;
}
/**
* Next we need a way to "pop" items off of the end of our list.
*
* Similar to push all we need to do is remove the value at the address at
* the end of our list. Then just decrement length.
*
* Popping an item from the end of a list is constant O(1) - "AWESOME!!"
*/
pop() {
// Don't do anything if we don't have any items.
if (this.length === 0) return;
// Get the last value, stop storing it, and return it.
var lastAddress = this.length - 1;
var value = this.memory[lastAddress];
delete this.memory[lastAddress];
this.length--;
// Also return the value so it can be used.
return value;
}
/**
* "push" and "pop" both operate on the end of a list, and overall are pretty
* simple operations because they don't need to be concerned with the rest of
* the list.
*
* Let's see what happens when we operate on the begining of the list with
* "unshift" and "shift".
*/
/**
* In order to add a new item at the beginning of our list, we need to make
* room for our value at the start by sliding all of the values over by one.
*
* [a, b, c, d, e]
* 0 1 2 3 4
* ⬊ ⬊ ⬊ ⬊ ⬊
* 1 2 3 4 5
* [x, a, b, c, d, e]
*
* In order to slide all of the items over we need to iterate over each one
* moving the prev value over.
*
* Because we have to iterate over every single item in the list:
*
* Unshifting an item to the start of a list is linear O(N) - "OKAY."
*/
unshift(value) {
// Store the value we are going to add to the start.
var previous = value;
// Iterate through each item...
for (var address = 0; address < this.length; address++) {
// replacing the "current" value with the "previous" value and storing the
// "current" value for the next iteration.
var current = this.memory[address];
this.memory[address] = previous;
previous = current;
}
// Add the last item in a new position at the end of the list.
this.memory[this.length] = previous;
this.length++;
}
/**
* Finally, we need to write a shift function to move in the opposite
* direction.
*
* We delete the first value and then slide through every single item in the
* list to move it down one address.
*
* [x, a, b, c, d, e]
* 1 2 3 4 5
* ⬋ ⬋ ⬋ ⬋ ⬋
* 0 1 2 3 4
* [a, b, c, d, e]
*
* Shifting an item from the start of a list is linear O(N) - "OKAY."
*/
shift() {
// Don't do anything if we don't have any items.
if (this.length === 0) return;
var value = this.memory[0];
// Iterate through each item...
for (var address = 0; address < this.length; address++) {
// and replace them with the next item in the list.
this.memory[address] = this.memory[address + 1];
}
// Delete the last item since it is now in the previous address.
delete this.memory[this.length - 1];
this.length--;
return value;
}
}
/**
* Lists are great for fast access and dealing with items at the end. However,
* as we've seen it isn't great at dealing with items not at the end of the
* list and we have to manually hold onto memory addresses.
*
* So let's take a look at a different data structure and how it deals with
* adding, accessing, and removing values without needing to know memory
* addresses.
*/
/*** ===================================================================== ***\
** - HASH TABLES --------------------------------------------------------- **
* ========================================================================= *
* ((\ *
* ( _ ,-_ \ \ *
* ) / \/ \ \ \ \ *
* ( /)| \/\ \ \| | .'---------------------'. *
* `~()_______)___)\ \ \ \ \ | .' '. *
* |)\ ) `' | | | .'-----------------------------'. *
* / /, | '...............................' *
* ejm | | / \ _____________________ / *
* \ / | |_) (_| | *
* \ / | | | | *
* ) / | | | | *
** / / (___) (___) **
\*** ===================================================================== ***/
/**
* Hash tables are an *unordered*, instead we have "keys" and "values" where we
* computed an address in memory using the key.
*
* The basic idea is that we have keys that are "hashable" (which we'll get to
* in a second) and can by used to add, access, and remove from memory very
* efficiently.
*
* var hashTable = new HashTable();
*
* hashTable.set('myKey', 'myValue');
* hashTable.get('myKey'); // >> 'myValue'
*/
class HashTable {
/**
* Again we're going to use a plain JavaScript array to represent our memory.
*/
constructor() {
this.memory = [];
}
/**
* In order to store key-value pairs in memory from our hash table we need a
* way to take the key and turn it into an address. We do this through an
* operation known as "hashing".
*
* Basically it takes a key and serializes it into a unique number for that
* key.
*
* hashKey("abc") => 96354
* hashKey("xyz") => 119193
*
* You have to be careful though, if you had a really big key you don't want
* to match it to a memory address that does not exist.
*
* So the hashing algorithm needs to limit the size, which means that there
* are a limited number of addresses for an unlimited number of values.
*
* The result is that you can end up with collisions. Places where two keys
* get turned into the same address.
*
* Any real world hash table implementation would have to deal with this,
* however we are just going to glaze over it and pretend that doesn't happen.
*/
/**
* Let's setup our "hashKey" function.
*
* Don't worry about understanding the logic of this function, just know that
* it accepts a string and outputs a (mostly) unique address that we will use
* in all of our other functions.
*/
hashKey(key) {
var hash = 0;
for (var index = 0; index < key.length; index++) {
// Oh look– magic.
var code = key.charCodeAt(index);
hash = ((hash << 5) - hash) + code | 0;
}
return hash;
}
/**
* Next, lets define our "get" function so we have a way of accessing values
* by their key.
*
* HashTable access is constant O(1) - "AWESOME!!"
*/
get(key) {
// We start by turning our key into an address.
var address = this.hashKey(key);
// Then we simply return whatever is at that address.
return this.memory[address];
}
/**
* We also need a way of adding data before we access it, so we will create
* a "set" function that inserts values.
*
* HashTable setting is constant O(1) - "AWESOME!!"
*/
set(key, value) {
// Again we start by turning the key into and address.
var address = this.hashKey(key);
// Then just set the value at that address.
this.memory[address] = value;
}
/**
* Finally we just need a way to remove items from our hash table.
*
* HashTable deletion is constant O(1) - "AWESOME!!"
*/
remove(key) {
// As always, we hash the key to get an address.
var address = this.hashKey(key);
// Then, if it exists, we `delete` it.
if (this.memory[address]) {
delete this.memory[address];
}
}
}
/**
* ============================================================================
* ,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'
* ============================================================================
*/
/**
* From this point going forward we are going to stop interacting directly with
* memory as the rest of these data structures start to be implemented with
* other data structures.
*
* These data structures focus on doing two things:
*
* - Organizing data based on how it is used
* - Abstracting away implementation details
*
* These data structures focus on creating an organization that makes sense for
* various types of programs. They insert a language that allows you discuss
* more complicated logic. All of this while abstracting away implementation
* details so that their implementation can change to be made faster.
*/
/*** ===================================================================== ***\
** - STACKS -------------------------------------------------------------- **
* ========================================================================= *
* _ . - - -- .. _ *
* |||| .-' /```\ `'-_ /| *
* |||| ( /`` \___/ ```\ ) | | *
* \__/ |`"-//..__ __..\\-"`| | | *
* || |`"||...__`````__...||"`| | | *
* || |`"||...__`````__...||"`| \ | *
* || _,.--|`"||...__`````__...||"`|--.,_ || *
* || .'` |`"||...__`````__...||"`| `'. || *
* || '. `/ |...__`````__...| \ .' || *
* || `'-..__ `` ````` `` __..-'` || *
* `""---,,,_______,,,---""` *
** **
\*** ===================================================================== ***/
/**
* Stacks are similar to lists in that they have an order, but they limit you
* to only pushing and popping values at the end of the list, Which as we saw
* before are very fast operations when mapping directly to memory.
*
* However, Stacks can also be implemented with other data structures in order
* to add functionality to them.
*
* The most common usage of stacks is places where you have one process adding
* items to the stack, and other process removing them from the end–
* prioritizing items added most recently.
*/
class Stack {
/**
* We're going to again be backed by a JavaScript array, but this time it
* represents a list like we implemented before rather than memory.
*/
constructor() {
this.list = [];
this.length = 0;
}
/**
* We're going to implement two of the functions from lists "push" and "pop"
* which are going to be identical in terms of functionality.
*/
/**
* Push to add items to the top of the stack.
*/
push(value) {
this.length++;
this.list.push(value);
}
/**
* And pop to remove items from the top of the stack.
*/
pop() {
// Don't do anything if we don't have any items.
if (this.length === 0) return;
// Pop the last item off the end of the list and return the value.
this.length--;
return this.list.pop();
}
/**
* We're also going to add a function in order to view the item at the top of
* the stack without removing it from the stack.
*/
peek() {
// Return the last item in "items" without removing it.
return this.list[this.length - 1];
}
}
/*** ===================================================================== ***\
** - QUEUES -------------------------------------------------------------- **
* ========================================================================= *
* /:""| ,@@@@@@. *
* |: oo|_ ,@@@@@`oo *
* C _) @@@@C _) *
* ) / "@@@@ '= *
* /`\\ ```)/ *
* || | | /`\\ *
* || | | || | \ *
* ||_| | || | / *
* \( ) | ||_| | *
* |~~~`-`~~~| |))) | *
* (_) | | (_) |~~~/ (_) *
* | |`""....__ __....""`| |`""...._|| / __....""`| | *
* | |`""....__`````__....""`| |`""....__`````__....""`| | *
* | | | ||``` | | ||`|`` | | *
* | | |_||__ | | ||_|__ | | *
* ,| |, jgs (____)) ,| |, ((;:;:) ,| |, *
** `---` `---` `---` **
\*** ===================================================================== ***/
/**
* Next we're going to build a queue which is complimentary to stacks. The
* difference is that this time you remove items from the start of the queue
* rather than the end. Removing the oldest items rather than the most recent.
*
* Again, because this limits the amount of functionality, there are many
* different ways of implementing it. A good way might be to use a linked list
* which we will see later.
*/
class Queue {
/**
* Again, our queue is using a JavaScript array as a list rather than memory.
*/
constructor() {
this.list = [];
this.length = 0;
}
/**
* Similar to stacks we're going to define two functions for adding and
* removing items from the queue. The first is "enqueue".
*
* This will push values to the end of the list.
*/
enqueue(value) {
this.length++;
this.list.push(value);
}
/**
* Next is "dequeue", instead of removing the item from the end of the list,
* we're going to remove it from the start.
*/
dequeue() {
// Don't do anything if we don't have any items.
if (this.length === 0) return;
// Shift the first item off the start of the list and return the value.
this.length--;
return this.list.shift();
}
/**
* Same as stacks we're going to define a "peek" function for getting the next
* value without removing it from the stack.
*/
peek() {
return this.list[0];
}
}
/**
* The important thing to note here is that because we used a list to back our
* queue it inherits the performance of "shift" which is linear O(N) "OKAY."
*
* Later we'll see linked lists that will allow us to implement a much faster
* Queue.
*/
/**
* ============================================================================
* ,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'`'-.,.-'
* ============================================================================
*/
/**
* From this point forward we're going to start dealing with data structures
* where the values of the data structure reference one another.
*
* +- Data Structure ---------------------------------------+
* | +- Item A ---------------+ +- Item B ---------------+ |
* | | Value: 1 | | Value: 2 | |
* | | Reference to: (Item B) | | Reference to: (Item A) | |
* | +------------------------+ +------------------------+ |
* +--------------------------------------------------------+
*
* The values inside the data structure become their own mini data structures
* in that they contain a value along with additional information including
* references to other items within the overall data structure.
*
* You'll see what I mean by this in a second.
*/
/*** ===================================================================== ***\
** - GRAPHS -------------------------------------------------------------- **
* ========================================================================= *
* *
* | RICK ASTLEY'S NEVER GONNA... *
* | +-+ *
* | +-+ |-| [^] - GIVE YOU UP *
* | |^| |-| +-+ [-] - LET YOU DOWN *
* | |^| |-| +-+ |*| [/] - RUN AROUND AND DESERT YOU *
* | |^| |-| +-+ |\| |*| [\] - MAKE YOU CRY *
* | |^| |-| |/| |\| +-+ |*| [.] - SAY GOODBYE *
* | |^| |-| |/| |\| |.| |*| [*] - TELL A LIE AND HURT YOU *
* | |^| |-| |/| |\| |.| |*| *
* +-------------------------------- *
** **
\*** ===================================================================== ***/
/**
* Contrary to the ascii art above, a graph is not a visual chart of some sort.
*
* Instead imagine it like this:
*
* A –→ B ←–––– C → D ↔ E
* ↑ ↕ ↙ ↑ ↘
* F –→ G → H ← I ––––→ J
* ↓ ↘ ↑
* K L
*
* We have a bunch of "nodes" (A, B, C, D, ...) that are connected with lines.
*
* These nodes are going to look like this:
*
* Node {
* value: ...,
* lines: [(Node), (Node), ...]
* }
*
* The entire graph will look like this:
*
* Graph {
* nodes: [
* Node {...},
* Node {...},
* ...
* ]
* }
*/
class Graph {
/**
* We'll hold onto all of our nodes in a regular JavaScript array. Not
* because there is any particular order to the nodes but because we need a
* way to store references to everything.
*/
constructor() {
this.nodes = [];
}
/**
* We can start to add values to our graph by creating nodes without any
* lines.
*/
addNode(value) {
this.nodes.push({
value: value,
lines: []
});
}
/**
* Next we need to be able to lookup nodes in the graph. Most of the time
* you'd have another data structure on top of a graph in order to make
* searching faster.
*
* But for our case we're simply going to search through all of nodes to find
* the one with the matching value. This is a slower option, but it works for
* now.
*/
find(value) {
return this.nodes.find(function(node) {
return node.value === value;
});
}
/**
* Next we can connect two nodes by making a "line" from one to the other.
*/
addLine(startValue, endValue) {
// Find the nodes for each value.
var startNode = this.find(startValue);
var endNode = this.find(endValue);
// Freak out if we didn't find one or the other.
if (!startNode || !endNode) {
throw new Error('Both nodes need to exist');
}
// And add a reference to the endNode from the startNode.
startNode.lines.push(endNode);
}
}
/**
* Finally you can use a graph like this:
*
* var graph = new Graph();
* graph.addNode(1);
* graph.addNode(2);
* graph.addLine(1, 2);
* var two = graph.find(1).lines[0];
*
* This might seem like a lot of work to do very little, but it's actually a
* quite powerful pattern, especially for finding sanity in complex programs.
*
* They do this by optimizing for the connections between data rather than
* operating on the data itself. Once you have one node in the graph, it's
* extremely simple to find all the related items in the graph.
*
* Tons of things can be represented this way, users with friends, the 800
* transitive dependencies in a node_modules folder, the internet itself is a
* graph of webpages connected together by links.
*/
/*** ===================================================================== ***\
** - LINKED LISTS -------------------------------------------------------- **
* ========================================================================= *
* _______________________ *
* ()=(_______________________)=() ,-----------------,_ *
* | | ," ", *
* | ~ ~~~~~~~~~~~~~ | ,' ,---------------, `, *
* | ,----------------------------, ,----------- *
* | ~ ~~~~~~~~ | | | *
* | `----------------------------' `----------- *
* | ~ ~~~~~~~~~~~~~ | `, `----------------' ,' *
* | | `, ,' *
* |_____________________| `------------------' *
* ()=(_______________________)=() *
** **
\*** ===================================================================== ***/
/**
* Next we're going to see how a graph-like structure can help optimize ordered
* lists of data.
*
* Linked lists are a very common data structure that is often used to
* implement other data structures because of its ability to efficiently add
* items to the start, middle, and end.
*
* The basic idea of a linked list is similar to a graph. You have nodes that
* point to other nodes. They look sorta like this:
*
* 1 -> 2 -> 3 -> 4 -> 5
*
* Visualizing them as a JSON-like structure looks like this:
*
* {
* value: 1,
* next: {
* value: 2,
* next: {
* value: 3,