-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1867 lines (1315 loc) · 118 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
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>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<title>Creative Coding</title>
<meta name="author" content="Sammy Steiner">
<meta name="description" content="Introduction Writing custom SQL queries is not something I have to do often, especially when most my database querying can be easily written with …">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="canonical" href="http://sammysteiner.github.io">
<link href="/favicon.png" rel="icon">
<link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<link href="/atom.xml" rel="alternate" title="Creative Coding" type="application/atom+xml">
<script src="/javascripts/modernizr-2.0.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="/javascripts/libs/jquery.min.js"%3E%3C/script%3E'))</script>
<script src="/javascripts/octopress.js" type="text/javascript"></script>
<!--Fonts from Google"s Web font directory at http://google.com/webfonts -->
<link href="//fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<link href="//fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<link href="//fonts.googleapis.com/css?family=Fjalla+One" rel="stylesheet" type="text/css">
<!--- MathJax Configuration -->
<script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</head>
<body class="collapse-sidebar sidebar-footer" >
<header role="banner"><hgroup>
<h1><a href="/">Creative Coding</a></h1>
<h2>A Creative Writer's Guide to Code</h2>
</hgroup>
</header>
<nav role="navigation"><ul class="subscribe" data-subscription="rss">
<li><a href="/atom.xml" rel="subscribe-rss" title="subscribe via RSS" target="_blank"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="25" height="25" viewbox="0 0 100 100"><path class="social" d="M 13.310204,73.332654 C 5.967347,73.332654 0,79.322448 0,86.621428 c 0,7.338776 5.967347,13.262246 13.310204,13.262246 7.370408,0 13.328572,-5.92245 13.328572,-13.262246 0,-7.29898 -5.958164,-13.288774 -13.328572,-13.288774 z M 0.01530612,33.978572 V 53.143878 C 12.493878,53.143878 24.229592,58.02347 33.068368,66.865306 41.894898,75.685714 46.767346,87.47449 46.767346,100 h 19.25 C 66.017346,63.592858 36.4,33.979592 0.01530612,33.978572 l 0,0 z M 0.03877552,0 V 19.17449 C 44.54796,19.17551 80.77551,55.437756 80.77551,100 H 100 C 100,44.87653 55.15102,0 0.03877552,0 z"></path></svg></a></li>
</ul>
<form action="https://www.google.com/search" method="get">
<fieldset role="search">
<input type="hidden" name="sitesearch" value="sammysteiner.github.io" />
<input class="search" type="text" name="q" results="0" placeholder="Search"/>
</fieldset>
</form>
<ul class="main-navigation">
<li><a href="/">Blog</a></li>
<li><a href="/blog/archives">Archives</a></li>
</ul>
</nav>
<div id="main">
<div id="content">
<div class="blog-index">
<article>
<header>
<h1 class="entry-title"><a href="/blog/2017/08/10/custom-sql-part-one/">Custom SQL: Part One</a></h1>
<p class="meta">
<time class='entry-date' datetime='2017-08-10T18:30:06-04:00'><span class='date'><span class='date-month'>Aug</span> <span class='date-day'>10</span><span class='date-suffix'>th</span>, <span class='date-year'>2017</span></span> <span class='time'>6:30 pm</span></time>
</p>
</header>
<div class="entry-content"><h2>Introduction</h2>
<p>Writing custom SQL queries is not something I have to do often, especially when most my database querying can be easily written with Rail’s Active Record library. However, every now and then, whether for performance or just utility, I need to write some custom SQL. Since those times are few and far in-between, I’m going to write a helpful four-part series with the basics: setting up tables, simple queries, aggregate functions, and joining tables. Here we go!</p>
<h2>Database Table Basics</h2>
<p>A database table looks very similar to an excel spreadsheet. You have rows and columns. Columns contain information about your entries and rows contain each individual entry. Each row should start with a unique ID that we use to identify the entry, called the Primary Key. The primary key is always an integer. There are many other data types available to us, aside from integers, some basic ones are: text, booleans, and dates.</p>
<h2>Creating a table</h2>
<p>If I wanted to create a table for all the pets my friends and I have, we’d want to have a couple tables. First and owners table that would just have an id, and a name for each person. Second we’d want to have a pets table with the name, age, adoption_date, and friendly columns. Here’s the SQL to create those tables:</p>
<p>The owner’s table:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='SQL'><span class='line'><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">owners</span> <span class="p">(</span>
</span><span class='line'><span class="n">id</span> <span class="nb">INTEGER</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
</span><span class='line'><span class="n">name</span> <span class="nb">TEXT</span>
</span><span class='line'><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>The pet’s table:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='SQL'><span class='line'><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">pets</span> <span class="p">(</span>
</span><span class='line'><span class="n">id</span> <span class="nb">INTEGER</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
</span><span class='line'><span class="n">name</span> <span class="nb">TEXT</span><span class="p">,</span>
</span><span class='line'><span class="n">age</span> <span class="nb">INTEGER</span><span class="p">,</span>
</span><span class='line'><span class="n">adoption_date</span> <span class="nb">DATE</span><span class="p">,</span>
</span><span class='line'><span class="n">friendly</span> <span class="nb">BOOLEAN</span>
</span><span class='line'><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>Quick thing to notice is that each command in SQL is concluded with a semi-colon. Let’s add some pets and owners:</p>
<p>The owner’s table:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='SQL'><span class='line'><span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">owners</span> <span class="p">(</span><span class="n">name</span><span class="p">)</span> <span class="k">VALUES</span> <span class="p">(</span><span class="s1">'Sammy'</span><span class="p">),</span> <span class="p">(</span><span class="s1">'Sally'</span><span class="p">),</span> <span class="p">(</span><span class="s1">'Sarah'</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>The pet’s table:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='SQL'><span class='line'><span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">pets</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">age</span><span class="p">,</span> <span class="n">adoption_date</span><span class="p">,</span> <span class="n">friendly</span><span class="p">)</span> <span class="k">VALUES</span> <span class="p">(</span><span class="s1">'Spot'</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2015</span><span class="o">-</span><span class="mi">01</span><span class="o">-</span><span class="mi">15</span><span class="p">,</span> <span class="s1">'true'</span><span class="p">),</span> <span class="p">(</span><span class="s1">'Scruffy'</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">2012</span><span class="o">-</span><span class="mi">06</span><span class="o">-</span><span class="mi">01</span><span class="p">,</span> <span class="s1">'true'</span><span class="p">),</span> <span class="p">(</span><span class="s1">'Slappy'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">2017</span><span class="o">-</span><span class="mi">01</span><span class="o">-</span><span class="mi">01</span><span class="p">,</span> <span class="s1">'false'</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>Now you’ll notice we haven’t stored any indication of who owns which pet. I could edit pets table to include an owners column like this:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='SQL'><span class='line'><span class="k">ALTER</span> <span class="k">TABLE</span> <span class="n">pets</span> <span class="k">ADD</span> <span class="n">owner_id</span> <span class="nb">INTEGER</span>
</span></code></pre></td></tr></table></div></figure>
<p>However, what happens when I want to share a pet with Sally? We can’t have an array of owner ids in the owners column on the pets table. The solution is to create a new table that stores those relationships. Each entry will represent a pet to owner relationship with a primary key, a owner_id column, and a pet_id column. That means that if Sally and I share a pet, there will be an entry for her relationship with the pet and an entry with my relationship with the pet. This is called a join table.</p>
<p>Join table:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='SQL'><span class='line'><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">owners_pets</span> <span class="p">(</span>
</span><span class='line'><span class="n">id</span> <span class="nb">INTEGER</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
</span><span class='line'><span class="n">owner_id</span> <span class="nb">INTEGER</span><span class="p">,</span>
</span><span class='line'><span class="n">pet_id</span> <span class="nb">INTEGER</span>
</span><span class='line'><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>Now let’s add some relationships:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='SQL'><span class='line'><span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">owners_pets</span> <span class="p">(</span><span class="n">owner_id</span><span class="p">,</span> <span class="n">pet_id</span><span class="p">)</span> <span class="k">VALUES</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">)(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<h2>Conclusion</h2>
<p>We’ve built three tables and populated them with some info, all in bespoke, handwritten SQL! Great job. Our next post will deal with querying those tables to get back some information.</p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/2017/07/28/the-big-o/">The Big O</a></h1>
<p class="meta">
<time class='entry-date' datetime='2017-07-28T17:47:08-04:00'><span class='date'><span class='date-month'>Jul</span> <span class='date-day'>28</span><span class='date-suffix'>th</span>, <span class='date-year'>2017</span></span> <span class='time'>5:47 pm</span></time>
</p>
</header>
<div class="entry-content"><h2>What is the O?</h2>
<p>As a developer working with real world systems, it is not always enough to solve the problem. We need to solve the problem as efficiently as possible. That means reducing the cost of our calculations. In order to think about this, we need some vocabulary, so let’s define our terms.</p>
<p>Cost is being valued in the number of calculations the computer must do in a worst case scenario. This is another way of expressing <a href="https://en.wikipedia.org/wiki/Time_complexity">Time Complexity</a> in computer science. For example, if we have a function that looks at every letter of a string, the cost of the function is equal to the length of the string in the worst case, ie. where the function must go through the entire string before concluding.</p>
<p>That cost in the worst case scenario is called the “Big O”. In the example above, the Big O is represented by O(n) where ‘n’ is the length of the string.</p>
<h2>How do we calculate it?</h2>
<p>As the complexity of our inputs grow, how many more calculations does the computer have to go through to complete the function in the worst case scenario? That is what we’re looking to calculate. When calculating this, we’re only interested in the exponential growth, since linear or even geometric growth isn’t going to have a large impact on performance.</p>
<p>Mostly, we’re looking for how many times our function will need to loop through our inputs, whether they are arrays, linked lists, hashes or antying else.</p>
<p>Let’s take a couple of simple functions and talk through the Big O.</p>
<h2>What are some common examples?</h2>
<p>Big O(n)</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>function simpleSearch(target, array) {
</span><span class='line'> for(var i = 0; i < array.length; i++) {
</span><span class='line'> if(target === array[i]){
</span><span class='line'> return i
</span><span class='line'> }
</span><span class='line'> }
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>
<p>In the example above, in the worst case scenario our target is the last element in the array. If that were the case, our simpleSearch function would have to go through the entire array one time in order to complete its task. Because of that, the number of potential computations grows proportionally with the length of the array. Hence the Big O is ‘n’.</p>
<p>Big O(n<sup>2</sup>)</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>function sumSearch(target, array) {
</span><span class='line'> var sums = []
</span><span class='line'> for(var i = 0; i < array.length; i++) {
</span><span class='line'> for(var j = 0; j < array.length; j++) {
</span><span class='line'> if(i + j === target){
</span><span class='line'> sums.push([i, j])
</span><span class='line'> }
</span><span class='line'> }
</span><span class='line'> }
</span><span class='line'> return sums
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>
<p>In the example above, our function needs to go through the entire array every time is called. For each number in the array, it then needs to check each number in the array to see if the add up to the target. That nested loop within our loop means that the growth of the calculations necessary to complete the function grow at a rate of ‘n’ * ‘n’ with the growth of the length of the array.</p>
<p>Let’s end with another popular one, a binary search. Keep in mind that one requirement for a binary search is that the array is already sorted.</p>
<p>Big O(log(n))</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>function binarySearch(target, array){
</span><span class='line'> var min = 0
</span><span class='line'> var max = array.length - 1
</span><span class='line'> while( min <= max ){
</span><span class='line'> var guess = Math.floor( (min + max) / 2)
</span><span class='line'> if(target === array[guess]){
</span><span class='line'> return guess
</span><span class='line'> } else if( array[guess] < target ) {
</span><span class='line'> min = guess + 1
</span><span class='line'> } else if( array[guess] > target ){
</span><span class='line'> max = guess - 1
</span><span class='line'> }
</span><span class='line'> }
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>
<p>In this example, we’re cutting the length of the array in half every time we check the value. So if we have an array with 10 elements, we’re only looking up 4 elements in the worst case scenario. Which means that we’re performing less calculations than the total number elements in the array. That’s pretty cool!</p>
<h2>Conclusion</h2>
<p>There are lots of ways to solve a problem with code and they are not all equal. After solving the problem you’re working on, spend the time working out the Big O of the method and see if you can come up with something better.</p>
<p>Good luck and happy coding!</p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/2017/07/20/how-can-i-work-with-html-collections/">How Can I Work With HTML Collections?</a></h1>
<p class="meta">
<time class='entry-date' datetime='2017-07-20T08:52:36-04:00'><span class='date'><span class='date-month'>Jul</span> <span class='date-day'>20</span><span class='date-suffix'>th</span>, <span class='date-year'>2017</span></span> <span class='time'>8:52 am</span></time>
</p>
</header>
<div class="entry-content"><h2>What are HTML Collections?</h2>
<p>In vanilla javascript, when selecting elements from the DOM, either through <code>document.getElementById</code>, <code>document.getElementsByClassName</code>, <code>document.getElementsByName</code>, <code>document.getElementsByTagName</code>, or <code>document.getElementsByTagNameNS</code> the return value is an HTML collection. This is important because even though it looks like an array, it does not have the same prototypical methods. Also, and more importantly they are live DOM objects, meaning that if you modify them, you are directly modifying the DOM.</p>
<h2>What do we get for free?</h2>
<p>First off, the ability to modify the DOM directly is very useful but also a great place for bugs to slip in, so be careful in how you use it.</p>
<p>We also get access to one property and a several methods:
1. HTML collections have a ‘length’ property that can be called with <code>collection.length</code>, and it returns the number of elements in the collection.
2. HTML collections have an ‘item()’ method that can be called with <code>collection.item(index number of the item)</code>, and it returns the element at that index. If the index doesn’t exist, it will return ‘null’.
3. HTML collections have a ‘namedItem()’ method that can be called with <code>collection.namedItem(id or name)</code>, and it returns the element in the collection with the corresponding ‘id’ or if that doesn’t find anything, with the corresponding ‘name.’</p>
<h2>What don’t we get for free?</h2>
<p>An HTML collection is not an array, and that means we don’t have all the great array methods like, ‘forEach’, ‘map’, ‘filter’, etc. So how do we iterate over the collection?</p>
<p>First, you should know that there was something I didn’t mention in the ‘what do we get for free’ section, we can still use bracket notation to access elements in our collection! What’s the difference between that an the item method? If you try an access an element with an index that doesn’t exist, item() will return null and bracket notation will return undefined.</p>
<p>With bracket notation, we can use a for loop:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>for (var i = 0; i < collection.length; i++) {
</span><span class='line'> /* do something with collection[i] */
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>
<p>Alternatively, there is a way to convert a collection to an array, curtesy of <a href="https://stackoverflow.com/questions/222841/most-efficient-way-to-convert-an-htmlcollection-to-an-array">harpo</a> on stackoverflow.</p>
<p>with ECMAScript 5.1 and below:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>var collectionArr = [].slice.call(collection)</span></code></pre></td></tr></table></div></figure>
<p>with ECMAScript 6 and above:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>var collectionArr = Array.from(collection)</span></code></pre></td></tr></table></div></figure>
<p>Now you can operate on each collection element as if it were an element of this new array. You will still modify the DOM when you change these values.</p>
<h2>Conclusion</h2>
<p>A question that has come up a few times for me while working with vanilla javascript is when to work with an HTML collection as a collection vs. converting it to an array and working with it that way. I think this comes down to two considerations. First, is your goal to modify the DOM for some or all of the elements in the collection? If so, working with it as a collection seems more direct, and might be more efficient, though I haven’t seen a difference in practice. Second, if what you need to do can be accomplished in a simple ‘for loop’, then great, no need to convert it to an array. Otherwise, converting it to an array will probably save more headaches than the line of code necessary to convert it.</p>
<p>Good luck, hope this helps, and happy coding!</p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/2017/07/14/listening-to-javascript-adding-events/">Listening to Javascript: Adding Events</a></h1>
<p class="meta">
<time class='entry-date' datetime='2017-07-14T15:03:14-04:00'><span class='date'><span class='date-month'>Jul</span> <span class='date-day'>14</span><span class='date-suffix'>th</span>, <span class='date-year'>2017</span></span> <span class='time'>3:03 pm</span></time>
</p>
</header>
<div class="entry-content"><h2>Getting good at listening</h2>
<p>This seems to keep coming up in code challenges so I wanted to write about it. Usually this is a piece of a larger challenge, but sometimes these questions are really basic. Sometimes these questions get weird, like in a totally real interview I had:</p>
<p>Interviewer: I want a button to create an alert on the screen.<br/>
Me: Ok. Does this button submit a form, and is that what the alert is for? Should the alert display a message depending on where the user clicked or the state of the page?<br/>
Interviewer: No.<br/>
Me: Ok, great. I’ve got my laptop right here, I can do this in the console on a live webpage, maybe wikipedia.<br/>
( I’ve already got the wikipedia page for Dolphins open and I’m pressing ‘option’ + ‘command’ + ‘j’ )<br/>
Interviewer: No. On paper. And with all the HTML for a webpage, with the header and body information.
Me: Ok, ( a little deflated )</p>
<p>So let’s review how to add an event listeners in javascript and see if we can find some more depth here too. Read to the end for some bonus event listener things with React.js.</p>
<h2>Adding event listeners</h2>
<p>We need a few things in order to add an event listener. First, what do we want to attach the listener to? In vanilla javascript, we can user our <code>document.getElementBy...</code> functions to select a specific tag, class, name, or id. Second, we’ll need to know what kind of event to listen to, ie. a ‘click’, ‘submit’, ‘mouseover’, or something else. There’s a great list of all the events <a href="https://www.w3schools.com/jsref/dom_obj_event.asp">here</a>. Finally, we need a function. In the interview mentioned above, it was a simple alert message, however, we can do a lot here. We can even call named functions. Ok, the real last thing is whether we want our event propagation to capture or bubble, we’ll get into that a bit later.</p>
<p>Ok, we’re ready to start coding this up.</p>
<h2>It’s console time</h2>
<p>Let’s add some listeners to the wikipedia page for <a href="https://en.wikipedia.org/wiki/Dolphin">Dolphins</a>, they’re super smart animals and we should be listening to them.</p>
<p>Open up the console and type:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>document.getElementById('mw-content-text').addEventListener('click', function(){alert('hi')})</span></code></pre></td></tr></table></div></figure>
<p>Now click any of the interesting dolphin information. Yay, we get an alert with our message.</p>
<p>Note: if we try and remove the event listener with <code>document.getElementById('mw-content-text').removeEventListener('click', function(){alert('hi')})
</code>, that won’t work because the remove event listener method only works with named functions. Our alert function is an anonymous function. But don’t worry! If you want to get rid of that event handler, you just need to refresh the page.</p>
<h2>Who’s up first: propagation</h2>
<p>If we add the following listeners to our page, what do you think will happen when we click a paragraph?</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>document.getElementById('mw-content-text').addEventListener('click', function(){alert('hi')}, true)
</span><span class='line'>document.getElementsByClassName('mw-body')[0].addEventListener('click', function(){alert('hello')}, true)
</span><span class='line'>document.getElementById('mw-content-text').addEventListener('click', function(){alert('why, hello there')}, false)
</span><span class='line'>document.getElementsByClassName('mw-body')[0].addEventListener('click', function(){alert('salutations')}, false)</span></code></pre></td></tr></table></div></figure>
<p>When you click you’ll see:
1. ‘hello’
2. ‘hi’
3. ‘why, hello there’
4. ‘salutations’</p>
<p>The reason for this is that events bubble by default, which means we start with the most deeply nested element’s event, and go up the chain from there. When we set the capture variable to ‘true’, we instead start with the outermost DOM element and work our way down. We also see from this experiment that events that are captured take precedent over those that aren’t. You can experiment by implementing these listeners in different orders, but the outcome will be the same.</p>
<h2>Alternatives ( and why not to use them )</h2>
<p>You can also do this inline in your HTML element with an ‘onclick’ variable set to a function. This is not ideal as it could take your website longer to render, which would negatively impact the user experience.</p>
<p>Alternatively, you can add an inline listener in javascript with:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>document.getElementById('mw-content-text').onclick = function(){alert('this works!')}</span></code></pre></td></tr></table></div></figure>
<p>However, this will overwrite any other listeners written this way and this method doesn’t allow you to control the propagation. Bonus question: if you add this to the dolphins page, what will the new order be?</p>
<h2>We want to see the HTML</h2>
<p>For closure, this is what a simple html page would look like if it just had a button that created an alert:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class=''><span class='line'><!doctype html>
</span><span class='line'><html>
</span><span class='line'> <head>
</span><span class='line'> <meta charset="utf-8">
</span><span class='line'> <title>Code Challenge</title>
</span><span class='line'> </head>
</span><span class='line'> <body>
</span><span class='line'> <button type='btn' id='alert'>Alert Button</button>
</span><span class='line'> <script>
</span><span class='line'> document.getElementById('alert').addEventListener('click', function(event) { alert('hello') } )
</span><span class='line'> </script>
</span><span class='line'> </body>
</span><span class='line'></html></span></code></pre></td></tr></table></div></figure>
<p>This was pretty basic, but there are much more fun code challenges out there. One I tried recently that was tricky and fun is this one from <a href="https://taco-spolsky.github.io/">Trello</a>. Have fun and happy coding.</p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/2017/07/05/dynamic-forms-in-react-part-2/">Dynamic Forms in React: Part 2</a></h1>
<p class="meta">
<time class='entry-date' datetime='2017-07-05T11:14:22-04:00'><span class='date'><span class='date-month'>Jul</span> <span class='date-day'>5</span><span class='date-suffix'>th</span>, <span class='date-year'>2017</span></span> <span class='time'>11:14 am</span></time>
</p>
</header>
<div class="entry-content"><h2>Recap of Part 1</h2>
<p>In <a href="https://sammysteiner.github.io/blog/2017/07/02/dynamic-forms-in-react/">Part 1</a>, we talked about simple forms in React. Namely, we talked about controlling inputs, updating state, and handling submissions. All of that assumes our form is static and we know the shape of our state. ‘Shape’ in this context means the data contained in the state object, the keys, the types of values, etc.</p>
<p>In part two, we’re going to talk about a more complex form. This form needs a way to update itself, and because we want to control the inputs, the form needs a way to update the state. Finally, when we send off our state object to an API, we need to know how to deconstruct that state regardless of how many phases and actions a user added to our form.</p>
<p>Here’s our gif from Part 1 to demonstrate the kind of form interaction we’re going for:
<img src="/assets/goalForm.gif" alt="Dynamic form gif" /></p>
<h2>Designing the Form UX</h2>
<p>When writing code in react, I find it helpful to start with the design I want to implement. Starting from the design makes it really easy for me to think through the components I want to build, now to nest them, and what props they’ll need to work with.</p>
<p>The first part of the form i pretty standard. Each goal should have a title and a description. I find it really helpful to think about the description as the motivation behind the goal. ie. “I want to go to the gym twice a week to get in shape for the summer.” or “I want to go get ready to run a half marathon by September.” I find it’s really helpful to break down big goals into manageable bits of work, and give myself a set amount of time to finish my task. Deadlines are my friend!</p>
<p>This tells me I want a button in my form to add a “phase”. A phase should have a timeframe, a number of days within which I need to complete this task, and a button to create actions. Each time I press this button, I need a new input for a description of an action. So we are creating dynamic inputs inside dynamically created inputs in a form with controlled inputs. That was a pretty scary problem to start with. But I knew my next step and it seemed like a fun thought challenge. How do I model this data?</p>
<h2>Modeling the Data</h2>
<p>The process of defining my state took a couple iterations to determine the best way to structure my data so it would play nicely with my database and wouldn’t require more looping than necessary. I started with what was going to be static, since that was pretty simple.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'> state = {
</span><span class='line'> title: '',
</span><span class='line'> description: '',
</span><span class='line'> repeat: false,
</span><span class='line'> // Some way to show all our goals
</span><span class='line'> }</span></code></pre></td></tr></table></div></figure>
<p>Great that’s three quarters of our state defined! We’re 75% done with this.</p>
<p>We’re going to want to have a list of goals, in order so we know which comes first, second, etc. That means we want an array of goals. Each element of our goal array is going to need a phase length and a list of actions. That means each element of our goal array is going to be an object with two keys, “phase” and “actions”. Actions is going to be a list of descriptions, that sounds like an array.</p>
<p>Writing that out gives us this:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>goals: [
</span><span class='line'> {
</span><span class='line'> phase: '',
</span><span class='line'> actions: []
</span><span class='line'> }
</span><span class='line'>]</span></code></pre></td></tr></table></div></figure>
<p>When we start filling this up with goals, our state will eventually look like this:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class=''><span class='line'> state ={
</span><span class='line'> title: as a string,
</span><span class='line'> description: as a text area,
</span><span class='line'> repeat: true of false boolean,
</span><span class='line'> goals: [
</span><span class='line'> {
</span><span class='line'> phase: length as a number,
</span><span class='line'> actions: [
</span><span class='line'> description for action 1, description for action 2, etc.
</span><span class='line'> ]
</span><span class='line'> },
</span><span class='line'> {
</span><span class='line'> phase: length as a number,
</span><span class='line'> actions: [
</span><span class='line'> description for action 1, description for action 2, etc.
</span><span class='line'> ]
</span><span class='line'> },
</span><span class='line'> etc.
</span><span class='line'> ]
</span><span class='line'> }</span></code></pre></td></tr></table></div></figure>
<p>Ok, that looks reasonable! Now that we know what we want the state to look like, and how it will be modified at each step of our user’s journey through the form, we can start thinking through the code to make that happen.</p>
<h2>Sudo Code for the Form</h2>
<p>We’re just going to sudo code this for the blog because the actual code gets very long, and a bit hairy because I decided to put it inside a modal. If you want to check out the actual code, you can find a link to my repo <a href="https://github.com/SammySteiner/habits-client">here</a>.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class=''><span class='line'> <form onSubmit={send our form data to the API}>
</span><span class='line'> <input type='text' name='title' value={this.state.title} onChange={update the state with this change}/>
</span><span class='line'> <input type='text' name='description' value={this.state.title} onChange={update the state with this change}/>
</span><span class='line'> <input type='textArea' name='repeat' value={this.state.description} onChange={update the state with this change}/>
</span><span class='line'> <input type='checkbox' checked={this.state.repeat} onChange={update the state with this change}/>
</span><span class='line'> <button type='button' onClick={ call our add phase function }>Add Phase</button>
</span><span class='line'> <input type='submit' value='submit' name='Create Goal'/>
</span><span class='line'> < render all the Goal components based on the goals in the state >
</span><span class='line'> </form>
</span><span class='line'>
</span><span class='line'> addPhaseFunction(){
</span><span class='line'> copy the state
</span><span class='line'> add a new element to the goals array with the object we described above
</span><span class='line'> }</span></code></pre></td></tr></table></div></figure>
<p>Then we need to import a goal component that maps over each element of the goals array and displays a phase input that is controlled by the value of the phase key in the object of the goals array. We also need to pass that input a function to update the phase in the state on change.</p>
<p>Additionally our goal component needs to show a button similar to the “Add Phase” button, but this one will say Add action. It only needs to update the state by pushing an empty string onto the actions array in the object.</p>
<p>Finally, our goal component needs to map over the action components and display in input for each of them. It then needs to use that element in the actions array to control the state and pass that input a function to update that state.</p>
<p>This should update our state dynamically, add goal objects to our goals array, add action descriptions to the actions array of it’s associated goals in the goals array. Our form component will keep updating every time the state is set by showing the new components with the new buttons and inputs they are mapping over. And Voila, it works!</p>
<h2>Conclusion</h2>
<p>There are some pretty cool things you can do with react. This form was a really fun challenge, and I’m really proud of what I built and I learned a lot in the process. If you want to check out the app in action, you can find it <a href="https://habits-sammy-steiner.herokuapp.com/">here</a> hosted on heroku for free, so I apologize for the loading time.</p>
<p>Thanks for checking it out!</p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/2017/07/02/dynamic-forms-in-react/">Dynamic Forms in React: Part 1, Regular React Forms</a></h1>
<p class="meta">
<time class='entry-date' datetime='2017-07-02T22:11:18-04:00'><span class='date'><span class='date-month'>Jul</span> <span class='date-day'>2</span><span class='date-suffix'>nd</span>, <span class='date-year'>2017</span></span> <span class='time'>10:11 pm</span></time>
</p>
</header>
<div class="entry-content"><h2>What is a Nested Dynamic Form</h2>
<p>Sometimes a form needs to expect the unexpected. When that happens, when the user needs freedom and flexibility, old-school forms just wont cut it. For <a href="habits-sammy-steiner.herokuapp.comhttps://sammysteiner.github.io/blog/2017/07/05/dynamic-forms-in-react-part-2/">Habits</a>, I wanted to give the user the ability to add as many fields to the form as they needed to express their goal.</p>
<p>Habits is an activity tracking app that is part accountability through gamificaiton, part exploration of the quantified self, and part guided self betterment. When using the Goal creation form, users are encouraged to give their goal a name, as well as a brief description or motivational sentence. Then, users are asked to divide their goal into smaller, more manageable chunks, divided into phases of time, and each phase is comprised of various actions. When the goal is created, the user’s inputs are translated into a card that allows them to check off what they’ve accomplished toward their goal, divides up the work according to their schedule, and gives them insights into their progress.</p>
<p>In order to cover all that, our form needs to be very special. This is what it’s going to look like:</p>
<p><img src="/assets/goalForm.gif" alt="Dynamic form gif" /></p>
<p>But we won’t get to that in this post. In this post, we will go through the basics of React forms to get us up to speed for what’s coming in our next post.</p>
<h2>Standard Javascript Forms</h2>
<p>Let’s build a simple from to accept a ‘name’ input from the user and send if off to our database, in vanilla Javascript. Here’s what our form would look like.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'><form id="goal-form">
</span><span class='line'> <input type="text" id="name" name="name" />
</span><span class='line'> <input type="submit" value="submit">
</span><span class='line'></form></span></code></pre></td></tr></table></div></figure>
<p>Next we need to create an event handler on window.load to listen for the submit event and hanle sending our information to the api.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>document.querySelector("#goal-form").addEventListener("submit", function(e){
</span><span class='line'> e.preventDefault()
</span><span class='line'> // stop the form from submitting and refreshing the page
</span><span class='line'> // you can add some validations here
</span><span class='line'> var name = document.getElementById('name').value
</span><span class='line'> return createGoal(name)
</span><span class='line'> // calling some function that sends a post request to our api with the value of the name input.
</span><span class='line'>})</span></code></pre></td></tr></table></div></figure>
<p>That’s one way to do things in vanilla Javascript. It’s messy, slow, and not very efficient. Things can get even crazier when there are lots of elements on your page. Searching through all those DOM nodes can get expensive. And when we want to do something dynamic in our form, like in the example above, this process can get very complicated very quickly. React gives us a better way.</p>
<h2>Controlled inputs</h2>
<p>In React, we try and stay away from the DOM, and use the virtual DOM instead. This means that when we go and look at what the user entered in our form, instead of checking for the form input values in the DOM, we store it in temporary memory, in the React component’s state, and just grab it from there when we’re ready.</p>
<p>Our React state for a name input looks like this:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>...
</span><span class='line'>export default class GoalForm extends Component {
</span><span class='line'> constructor(){
</span><span class='line'> super()
</span><span class='line'> this.state = {
</span><span class='line'> name: ''
</span><span class='line'> }
</span><span class='line'> }
</span><span class='line'>}
</span><span class='line'>...</span></code></pre></td></tr></table></div></figure>
<p>All this does is create a GoalForm class component in React with a state object that has a value of ‘name’, which points to an empty string.</p>
<p>Instead of having the React component store the information of the user’s input and have the user’s input be stored in the DOM, which would break the single source of truth convention, we just have the component’s value display the state. That is called a controlled input.</p>
<p>Our form looks like this:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'><form onSubmit={this.handleSubmit.bind(this)}>
</span><span class='line'> <input label='name' type='text' value={this.state.name} onChange={this.handleChange.bind(this)} />
</span><span class='line'> <input type='submit' value='submit' />
</span><span class='line'></form></span></code></pre></td></tr></table></div></figure>
<p>This form has one text input field for a name, that shows the value of the name object in the component’s state. When a user enters something in the input field, that input is intercepted by our handleChange function, which updates the state, the Component is re-rendered, and the new state is shown as the value.</p>
<h2>Handling Changes and form Submission</h2>
<p>Our handleSubmit and handleChange functions look like this:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>handleSubmit(e){
</span><span class='line'> e.preventDefault()
</span><span class='line'> this.props.createGoal(this.state.name)
</span><span class='line'> // this is a function passed down from another component via props. In this case, it will send a post request to an api with the 'name' the user entered.
</span><span class='line'> this.setState({name: ''})
</span><span class='line'> // this.setState is a React function that sets the state of the current component to the argument that is passed in and it also forces the component to re-render.
</span><span class='line'>}
</span><span class='line'>
</span><span class='line'>handleChange(e){
</span><span class='line'> e.preventDefault()
</span><span class='line'> this.setState({name: e.target.value })
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>
<h2>Conclusion</h2>
<p>This is a lot to wrap your head around, controlled inputs, preventing a lot of default actions, completely sidestepping the DOM! I know, it’s a lot. But it’s about to get crazier. In part two, we’ll discuss how to give the user the ability to dynamically add inputs in this controlled system. Stay tuned for <a href="https://sammysteiner.github.io/blog/2017/07/05/dynamic-forms-in-react-part-2/">Part II</a>.</p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/2017/06/04/generate-unique-and-random-x-and-y-coordinates/">Building a Game: Generate Unique and Random X and Y Coordinates</a></h1>
<p class="meta">
<time class='entry-date' datetime='2017-06-04T12:39:18-04:00'><span class='date'><span class='date-month'>Jun</span> <span class='date-day'>4</span><span class='date-suffix'>th</span>, <span class='date-year'>2017</span></span> <span class='time'>12:39 pm</span></time>
</p>
</header>
<div class="entry-content"><h2>Why would I need some random coordinates?</h2>
<p>I want to build a game. This game is going to have a dungeon, represented by tiles on a game board, and it will be randomly populated with a door, a key, a bunch of monsters and the player’s starting position. My database schema is expecting an ‘x’ and ‘y’ coordinates for each of these, but to make my game work, I need to make sure that none of these start off on the same square. It wouldn’t be very challenging if the key and door could appear on the same spot. It wouldn’t be fun if the player spawned on the same tile as a monster and lost the game immediately! There are lots of reasons you might want to generate a number of unique ‘x’ and ‘y’ coordinates for a grid of a given size, this would work for all of them.</p>
<h2>What do I want my result to look like?</h2>
<p>We’re going to start simple and build out more complexity as we get things working. As I said, I need a coordinate for the door, a key, the player and some monsters, that’s a minimum of four coordinates and we need a board that is two squares by two squares to fit everything. In this case, I’m using all the possible coordinates, so I want my final outcome to look something like this hash of info:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>game_coordinates = {
</span><span class='line'> player: {x: 1, y: 1},
</span><span class='line'> door: {x:1, y:2},
</span><span class='line'> key: {x:2, y:1},
</span><span class='line'> monster: [
</span><span class='line'> {x: 2, y: 2}
</span><span class='line'> ]
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>
<p>Let’s zoom in on the first problem we want to solve. Getting ourselves the list of unique ‘x’ and ‘y’ coordinates. This sounds like we want to use an array, which we would ultimately need to iterate over to assign values. For now, our array should look like this:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>unique_coordinates = [[1,1], [1,2], [2,1], [2,2]]</span></code></pre></td></tr></table></div></figure>
<p>We will use this array later to assign the coordinates to the door, key, player, and monster. Let’s break down what we are seeing. This isn’t one simple array, it’s an array of arrays. Each of the nested arrays represents a unique set of ‘x’ and ‘y’ coordinates. We can also have two arrays for the x and the y values:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>x_values = [1, 1, 2, 2]
</span><span class='line'>y_values = [1, 1, 2, 2]</span></code></pre></td></tr></table></div></figure>
<p>If we look a little closer, the arrays shouldn’t both be in order like that. In our unique_coordinates array, they ‘x’ values repeat then increment while the ‘y’ values increment then repeat. So we want values that look like this:</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>x_values = [1, 1, 2, 2]
</span><span class='line'>y_values = [1, 2, 1, 2]</span></code></pre></td></tr></table></div></figure>
<h2>Let’s hard code this to get started</h2>
<p>Now that we have the basic building blocks for our data structure, let’s put it together assuming we have the unique values we need. In our two by two grid, with the x_values and y_values arrays, all we need to do is a simple loop to get our unique_coordinates array, and pull off four coordinates at random:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='Ruby'><span class='line'><span class="n">unique_coordinates_generator</span> <span class="o">=</span>
</span><span class='line'><span class="n">x_values</span><span class="o">.</span><span class="n">each_with_index</span><span class="o">.</span><span class="n">map</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="p">,</span> <span class="n">index</span><span class="o">|</span>
</span><span class='line'> <span class="o">[</span><span class="n">x</span><span class="p">,</span> <span class="n">y_values</span><span class="o">[</span><span class="n">index</span><span class="o">]]</span>
</span><span class='line'><span class="k">end</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
</span><span class='line'><span class="c1"># >>> [[1,1], [1,2], [2,1], [2,2]]</span>
</span></code></pre></td></tr></table></div></figure>
<p>Perfect! Just note that if you’re following along, your coordinates may be in a different order, that’s exactly what we want. They should all be unique.</p>
<p>To assign each of these to our game board objects, we can do this by assigning each a value from the unique_coordinates_generator. This isn’t the prettiest way to do this, but it will work.</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='Ruby'><span class='line'><span class="n">player</span> <span class="o">=</span> <span class="n">unique_coordinates_generator</span><span class="o">[</span><span class="mi">0</span><span class="o">]</span>
</span><span class='line'><span class="n">door</span> <span class="o">=</span> <span class="n">unique_coordinates_generator</span><span class="o">[</span><span class="mi">1</span><span class="o">]</span>
</span><span class='line'><span class="n">key</span> <span class="o">=</span> <span class="n">unique_coordinates_generator</span><span class="o">[</span><span class="mi">2</span><span class="o">]</span>
</span><span class='line'><span class="n">monsters</span> <span class="o">=</span> <span class="o">[</span> <span class="n">unique_coordinates_generator</span><span class="o">[</span><span class="mi">3</span><span class="o">]</span> <span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>
<p>this looks great. The next step is to abstract this to handle grids of any size, with more than four coordinates to accommodate multiple monsters.</p>
<h2>Abstraction</h2>
<p>To state our problem here more simply, we want to create our x_values and y_values arrays for grids larger than two by two. That means, the size of the grid would need to be an argument. Additionally we can infer from the fact that we need to accommodate a variable number of monsters that the number of monsters will also be an argument. So the skeleton of our code should look something like this:</p>
<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='Ruby'><span class='line'><span class="k">def</span> <span class="nf">coord_generator</span><span class="p">(</span><span class="n">grid_size</span><span class="p">,</span> <span class="n">number_of_monsters</span><span class="p">)</span>
</span><span class='line'> <span class="c1"># some code that creates:</span>