-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1341 lines (873 loc) · 82.7 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>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tim Taubert - Mozillian. Open Source enthusiast. Loves programming languages.</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta name="description" content="Scotland.JS 2013 in Edinburgh May, 14th 2013 I got to spend Wednesday through Friday in Edinburgh last week to attend
Scotland.JS. Edinburgh is a …">
<meta content="Tim Taubert" name="author">
<link href="http://fonts.googleapis.com/css?family=Droid+Sans:400,700|PT+Sans" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/screen.css" media="screen" rel="stylesheet" type="text/css">
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<![endif]-->
<link href="/favicon.ico" rel="icon" type="image/ico">
<link href="/atom.xml" rel="alternate" title="Tim Taubert" type="application/atom+xml">
<script defer src="/javascripts/main.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="col span3">
<header id="header">
<h1><a href="/">Tim Taubert</a></h1>
</header>
<section id="about">
<h1 class="hidden">About me</h1>
<strong>Mozillian.</strong>
<strong>Open Source enthusiast.</strong>
<strong>Loves Programming Languages.</strong>
</section>
<nav>
<h1 class="hidden">Main Navigation</h1>
<ul class="nav-main">
<li><a class="nav-main-link" title="About me" href="/about-me">about me</a></li>
<li><a class="nav-main-link" title="Imprint" href="/imprint">imprint</a></li>
</ul>
</nav>
</div>
<div id="main" class="col span6">
<section>
<h1 class="hidden">Content</h1>
<article class="post">
<header class="article-header">
<h1><a href="/blog/2013/05/scotland-js-2013-in-edinburgh/" title="Scotland.JS 2013 in Edinburgh">Scotland.JS 2013 in Edinburgh</a></h1>
<time datetime="2013-05-14T08:00:00+02:00" pubdate data-updated="true">May, 14<span>th</span> 2013</time>
</header>
<p>I got to spend Wednesday through Friday in Edinburgh last week to attend
<a href="http://www.scotlandjs.com/">Scotland.JS</a>. Edinburgh is a lovely city and I will
definitely return to get to know it better. It has great people, beers, food and
even a castle - what could one want more?</p>
<p>I arrived on Wednesday, just in time for the
<a href="http://techmeetup.co.uk/">TechMeetup</a>. It took place in the Appleton Tower and
had about 70-80 attendees with quite diverse technical backgrounds. I had a very
interesting talk to a freelance patent attorney and also met a couple of people
I knew from recent conferences and meetups in Berlin. After we were out of free
pizza and beers we met most of the Scotland.JS attendees in a pub right next to
the Appleton Tower. Cue more beers and tech conversations.</p>
<p>Thursday was the first day of Scotland.JS that started with
<a href="http://decadecity.net/blog/2013/05/09/jan-lehnardt-scotlandjs-opening-keynote">a great keynote</a>
from <a href="https://twitter.com/janl">Jan Lehnardt</a>. The most memorable talk of the
day was about
<a href="http://decadecity.net/blog/2013/05/09/philip-roberts-enemy-state-introduction-functional-reactive-programming-and-baconjs">Functional Reactive Programming using Bacon.js</a>
by <a href="https://twitter.com/philip_roberts">Philip Roberts</a>. There of course were a
lot more great talks but the possibilities of creating and combining event
streams kept my head spinning the most. At the end of the day we again went to a
neat pub near the venue and I headed to bed rather early, still a little tired
from travel and the day before.</p>
<p><img src="/images/scotlandjs.jpg" title="Scotland.JS organizer Peter Aitken on stage" ></p>
<p>Friday started with a short 20-minute walk through Edinburgh’s old town that I
needed to pass on my way to the venue. My favorite talk of the second and last
day was held by <a href="https://twitter.com/dominictarr">Dominic Tarr</a> that tought us
about
<a href="http://decadecity.net/blog/2013/05/10/dominic-tarr-database-future-leveldb">the internals of leveldb</a>.
I also really enjoyed <a href="https://twitter.com/maboa">Mark Boas</a> talking about
<a href="http://happyworm.com/slides/scotlandjs2013/">making audio a first-class citizen of the web</a>
- a very entertaining and impressive mix of technologies. A GitHub drinkup in
the venue’s own pub was a great way to end the conference - lots of good
conversations with Scotland.JS attendees and speakers as well as people from the
local tech community and visitors of the Scottish Ruby Conf.</p>
<p>I flew home the very next day and already miss Edinburgh with its neat little
alleys and pubs everywhere. The JavaScript community has once again shown its
value as a very interesting mix of nice welcoming people coming from so many
different technical backgrounds. Like after most conferences I feel a little
exhausted and my head is full of ideas for future or current (side-)projects. I
will try my best to return next year, it has been a lot of fun!</p>
</article>
<article class="post">
<header class="article-header">
<h1><a href="/blog/2013/05/working-with-infinite-sequences-in-javascript/" title="Working with infinite sequences in JavaScript">Working with infinite sequences in JavaScript</a></h1>
<time datetime="2013-05-06T12:00:00+02:00" pubdate data-updated="true">May, 6<span>th</span> 2013</time>
</header>
<p>JavaScript comes with most of the little functional tools you need to work on
finite sequences that are usually implemented using Arrays. Array.prototype
includes a number of methods like <em>map()</em> and <em>filter()</em> that apply a given
function to all items of the Array and return the resulting new Array.</p>
<figure class='code'> <div class="highlight"><pre><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">3</span><span class="p">].</span><span class="nx">map</span><span class="p">(</span><span class="nx">x</span> <span class="o">=></span> <span class="nx">x</span> <span class="o">+</span> <span class="mi">1</span><span class="p">);</span> <span class="c1">// result: [2, 3, 4];</span>
</pre></div></figure>
<p>These tools however are not a good fit for infinite sequences as they always
consume the whole sequence at once to return a new one. Implementing infinite
sequences by yourself means you would have to come up with your own API that
clients need to adhere to. You often would keep state variables whose values
need to be maintained for the duration of the computation process.</p>
<h2>Generators to the rescue</h2>
<p>Using ES6
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:generators">generators</a>
implementing the infinite sequence of all natural numbers turns out to be a
trivial task. We even have language support to iterate over them.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span><span class="o">*</span> <span class="nx">nat</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">while</span> <span class="p">(</span><span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nx">i</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">num</span> <span class="k">of</span> <span class="nx">nat</span><span class="p">())</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">num</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// prints 1 2 3 4 ...</span>
</pre></div></figure>
<p>Now that we have a first infinite set we need a couple of functions that help us
working with, combining, and building new sequences.</p>
<h2>Mapping</h2>
<p>Let us start with <em>map()</em> - a function at the very heart of functional
programming. It builds a new sequence by applying a function to all elements of
a given sequence.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span><span class="o">*</span> <span class="nx">map</span><span class="p">(</span><span class="nx">it</span><span class="p">,</span> <span class="nx">f</span><span class="p">)</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">x</span> <span class="k">of</span> <span class="nx">it</span><span class="p">)</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<p>Using the generator implementation of <em>map()</em> we can now easily write a function
called <em>squares()</em> that represents the set of squares of all natural numbers
(1², 2², 3², …, n²).</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">squares</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">map</span><span class="p">(</span><span class="nx">nat</span><span class="p">(),</span> <span class="nx">x</span> <span class="o">=></span> <span class="nx">x</span> <span class="o">*</span> <span class="nx">x</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">num</span> <span class="k">of</span> <span class="nx">squares</span><span class="p">())</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">num</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// prints 1 4 9 16 ...</span>
</pre></div></figure>
<p>As we are using
<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of">for…of</a>
we can also pass an Array to <em>map()</em> to retrieve a new generator with a finite
source. The given function is applied to value after value instead of to all
values at once when using <em>Array.prototype.map</em>.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">let</span> <span class="nx">squares</span> <span class="o">=</span> <span class="nx">map</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">3</span><span class="p">],</span> <span class="nx">x</span> <span class="o">=></span> <span class="nx">x</span> <span class="o">*</span> <span class="nx">x</span><span class="p">);</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">num</span> <span class="k">of</span> <span class="nx">squares</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">num</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// prints 1 4 9</span>
</pre></div></figure>
<h2>Filtering</h2>
<p>Another common task is filtering specific values from a sequence. Our custom
implementation of <em>filter()</em> takes an iterator and a predicate - the returned
sequence will consist of all items of the original one for which the predicate
holds.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span><span class="o">*</span> <span class="nx">filter</span><span class="p">(</span><span class="nx">it</span><span class="p">,</span> <span class="nx">f</span><span class="p">)</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">x</span> <span class="k">of</span> <span class="nx">it</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="p">))</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nx">x</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<p>We can now use <em>filter()</em> to create the set of all even natural numbers.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">even</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">filter</span><span class="p">(</span><span class="nx">nat</span><span class="p">(),</span> <span class="nx">x</span> <span class="o">=></span> <span class="nx">x</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">===</span> <span class="mi">0</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">num</span> <span class="k">of</span> <span class="nx">even</span><span class="p">())</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">num</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// prints 2 4 6 8 ...</span>
</pre></div></figure>
<p>A common derivation from <em>filter()</em> is <em>filterNot()</em> that simply negates the
given predicate. We can use that to implement <em>even()</em> as well.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">filterNot</span><span class="p">(</span><span class="nx">it</span><span class="p">,</span> <span class="nx">f</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">filter</span><span class="p">(</span><span class="nx">it</span><span class="p">,</span> <span class="nx">x</span> <span class="o">=></span> <span class="o">!</span><span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="p">));</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">even</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">filterNot</span><span class="p">(</span><span class="nx">nat</span><span class="p">(),</span> <span class="nx">x</span> <span class="o">=></span> <span class="nx">x</span> <span class="o">%</span> <span class="mi">2</span><span class="p">);</span>
<span class="p">}</span>
</pre></div></figure>
<h2>Mersenne primes</h2>
<p>Suppose we were to implement a sequence that represents all
<a href="https://en.wikipedia.org/wiki/Mersenne_prime">Mersenne prime numbers</a>.
Mersenne primes are defined as prime numbers of the form M<sub>n</sub> = 2<sup>n</sup> - 1,
that is the set of all numbers of the given form that have no positive divisors
other than 1 and themselves. The set of Mersenne primes is
<a href="https://en.wikipedia.org/wiki/Lenstra%E2%80%93Pomerance%E2%80%93Wagstaff_conjecture">assumed to be infinite</a>
though this remains unproven, yet.</p>
<p>Let us first define some helper functions. <em>range(from, to)</em> and <em>forall()</em> are
common helpers in functional programming languages. <em>range()</em> returns the set of
natural numbers in a given range. <em>forall()</em> returns whether the given predicate
holds for all items in the sequence and should therefore only be used for finite
sequences.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span><span class="o">*</span> <span class="nx">range</span><span class="p">(</span><span class="nx">lo</span><span class="p">,</span> <span class="nx">hi</span><span class="p">)</span> <span class="p">{</span>
<span class="k">while</span> <span class="p">(</span><span class="nx">lo</span> <span class="o"><=</span> <span class="nx">hi</span><span class="p">)</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nx">lo</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">forall</span><span class="p">(</span><span class="nx">it</span><span class="p">,</span> <span class="nx">f</span><span class="p">)</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">x</span> <span class="k">of</span> <span class="nx">it</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="p">))</span> <span class="p">{</span>
<span class="k">return</span> <span class="kc">false</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">}</span>
</pre></div></figure>
<p><em>mersenneNumbers()</em> is the set of all numbers of the form M<sub>n</sub> = 2<sup>n</sup> - 1.
<em>isPrime()</em> is a very simple and naive (and slow) primality checker that returns
whether the given candidate is divisible by any of the numbers in the range of
[2, candidate - 1]. We will use <em>isPrime()</em> as a filter to remove all non-prime
numbers from <em>mersenneNumbers()</em>.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">mersenneNumbers</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">map</span><span class="p">(</span><span class="nx">nat</span><span class="p">(),</span> <span class="nx">x</span> <span class="o">=></span> <span class="nb">Math</span><span class="p">.</span><span class="nx">pow</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="nx">x</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">mersennePrimes</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">function</span> <span class="nx">isPrime</span><span class="p">(</span><span class="nx">n</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">forall</span><span class="p">(</span><span class="nx">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="nx">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">),</span> <span class="nx">x</span> <span class="o">=></span> <span class="nx">n</span> <span class="o">%</span> <span class="nx">x</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">return</span> <span class="nx">filter</span><span class="p">(</span><span class="nx">mersenneNumbers</span><span class="p">(),</span> <span class="nx">isPrime</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">mprime</span> <span class="k">of</span> <span class="nx">mersennePrimes</span><span class="p">())</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">mprime</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// prints 3 7 31 127 ...</span>
</pre></div></figure>
<h2>Flattening</h2>
<p>As a last example we will implement a function that flattens nested sequences.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span><span class="o">*</span> <span class="nx">flatten</span><span class="p">(</span><span class="nx">it</span><span class="p">)</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">x</span> <span class="k">of</span> <span class="nx">it</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="nx">x</span><span class="p">[</span><span class="s2">"@@iterator"</span><span class="p">])</span> <span class="o">==</span> <span class="s2">"function"</span><span class="p">)</span> <span class="p">{</span>
<span class="k">yield</span><span class="o">*</span> <span class="nx">flatten</span><span class="p">(</span><span class="nx">x</span><span class="p">);</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nx">x</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<p>Note that using <em>for…of</em> comes in handy again as we can use it to iterate
over Arrays and generators. Using <em>flatten()</em> we can now do:</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">let</span> <span class="nx">it</span> <span class="o">=</span> <span class="nx">flatten</span><span class="p">([</span><span class="mi">1</span><span class="p">,</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="p">[[</span><span class="mi">4</span><span class="p">],</span> <span class="p">[</span><span class="mi">5</span><span class="p">]]]);</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">num</span> <span class="k">of</span> <span class="nx">it</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">num</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// prints 1 2 3 4 5</span>
</pre></div></figure>
<p>Combining <em>flatten()</em> and <em>map()</em> to <em>flatMap()</em> we can implement another very
common function that flattens the result of applying a given function to all
items of a sequence. Let us use it to re-build the set of all natural numbers
from the set of all even natural numbers.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">flatMap</span><span class="p">(</span><span class="nx">it</span><span class="p">,</span> <span class="nx">f</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">flatten</span><span class="p">(</span><span class="nx">map</span><span class="p">(</span><span class="nx">it</span><span class="p">,</span> <span class="nx">f</span><span class="p">));</span>
<span class="p">}</span>
<span class="kd">let</span> <span class="nx">it</span> <span class="o">=</span> <span class="nx">flatMap</span><span class="p">(</span><span class="nx">even</span><span class="p">(),</span> <span class="nx">x</span> <span class="o">=></span> <span class="p">[</span><span class="nx">x</span> <span class="o">-</span> <span class="mi">1</span><span class="p">,</span> <span class="nx">x</span><span class="p">]);</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">num</span> <span class="k">of</span> <span class="nx">it</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">num</span><span class="p">);</span>
<span class="p">}</span>
<span class="c1">// prints 1 2 3 4 ...</span>
</pre></div></figure>
<h2>Generators are powerful</h2>
<p>It is quite obvious that studying ES6 generators really repays. Thanks to Andy
Wingo these are available in the latest versions of
<a href="http://wingolog.org/archives/2013/10/07/es6-generators-and-iteration-in-spidermonkey">Firefox</a> and
<a href="http://wingolog.org/archives/2013/05/08/generators-in-v8">Chrome</a>. They will be
in the toolbox of every professional JavaScript developer soon and I am sure we
can count on the community to come up with lots of great uses and libraries.</p>
</article>
<article class="post">
<header class="article-header">
<h1><a href="/blog/2013/05/stop-iteration-time/" title="Stop. Iteration time!">Stop. Iteration time!</a></h1>
<time datetime="2013-05-03T18:00:00+02:00" pubdate data-updated="true">May, 3<span>rd</span> 2013</time>
</header>
<p>You have probably already heard of
<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Iterators_and_Generators">generators and iterators</a>
coming to a browser near you. They have been available in Firefox for a long
time and are used extensively all over the Mozilla code base. The V8 team
will implement iterators and generators
<a href="http://code.google.com/p/v8/issues/detail?id=2355">once ES6 has been finalized</a>.</p>
<p>This post describes the current implementation in SpiderMonkey and tries to
include the current state of the ES6 draft and discussions.</p>
<h2>A simple generator</h2>
<p>Let us take a look at a simple example of a generator function that represents
an infinite sequence containing all the numbers from 0 to <em>Number.MAX_VALUE</em>.
Once it reaches <em>MAX_VALUE</em> it will not increase any further but always return
the same number.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">myInfiniteGenerator</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">while</span> <span class="p">(</span><span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nx">i</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="kd">var</span> <span class="nx">iter</span> <span class="o">=</span> <span class="nx">myInfiniteGenerator</span><span class="p">();</span>
<span class="k">while</span> <span class="p">(</span><span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">iter</span><span class="p">.</span><span class="nx">next</span><span class="p">());</span>
<span class="p">}</span>
</pre></div></figure>
<p>Any object of the following shape is an
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:iterators">iterator</a>:</p>
<figure class='code'> <div class="highlight"><pre><span class="p">{</span> <span class="nx">next</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="o">-></span> <span class="nx">any</span> <span class="p">}</span>
</pre></div></figure>
<p>The <em>next()</em> method simply returns the item next in the sequence.</p>
<h2>Finite sequences</h2>
<p>As you surely noticed the generator of the first example produces iterators that
will never run out of items. The next example shows an iterator representing a
finite sequence:</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">MyFiniteIterator</span><span class="p">(</span><span class="nx">max</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">cur</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="nx">max</span> <span class="o">=</span> <span class="nx">max</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">MyFiniteIterator</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">next</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">cur</span> <span class="o"><</span> <span class="k">this</span><span class="p">.</span><span class="nx">max</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">cur</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">throw</span> <span class="nx">StopIteration</span><span class="p">;</span>
<span class="p">};</span>
</pre></div></figure>
<p>The given code implements a custom iterator without writing a generator
function. Note that it throws <em>StopIteration</em> as soon as it reaches the maximum
value to signal that the sequence is exhausted. It is a lot more elegant to
implement the same sequence using a generator function:</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">myFiniteGenerator</span><span class="p">(</span><span class="nx">max</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">while</span> <span class="p">(</span><span class="nx">i</span> <span class="o"><</span> <span class="nx">max</span><span class="p">)</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nx">i</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<p>Generator functions will automatically throw <em>StopIteration</em> when terminating.
So how should one consume iterators with finite sequences?</p>
<h2>Consuming sequences</h2>
<p>In Java for example, you would check <em>iter.hasNext()</em> and stop when it returns
false. In JavaScript however you need to use a <em>try…catch</em> statement to catch
<em>StopIteration</em> when it is being thrown.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">iter</span> <span class="o">=</span> <span class="nx">myFiniteGenerator</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span>
<span class="k">while</span> <span class="p">(</span><span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
<span class="k">try</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">iter</span><span class="p">.</span><span class="nx">next</span><span class="p">());</span>
<span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">e</span> <span class="k">if</span> <span class="nx">e</span> <span class="o">===</span> <span class="nx">StopIteration</span><span class="p">)</span> <span class="p">{</span>
<span class="k">break</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<p>You might wonder if there is a better way to do this and indeed there is. Using
<em>for…in</em> or <em>for…of</em> you do not have to catch <em>StopIteration</em> yourself, the
JavaScript engine will do it for you. As soon as the sequence is exhausted the
loop will terminate normally without the exception being propagated:</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">iter</span> <span class="o">=</span> <span class="nx">myFiniteGenerator</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="k">in</span> <span class="nx">iter</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">i</span><span class="p">);</span>
<span class="p">}</span>
</pre></div></figure>
<h2>StopIteration is special</h2>
<p><em>StopIteration</em> actually is a standard variable that is bound to an object of
class <em>StopIteration</em>. It is an ordinary object with no properties of its own
and it is not a constructor function.</p>
<figure class='code'> <div class="highlight"><pre><span class="k">try</span> <span class="p">{</span>
<span class="k">throw</span> <span class="nx">StopIteration</span><span class="p">;</span>
<span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">e</span> <span class="k">if</span> <span class="nx">e</span> <span class="k">instanceof</span> <span class="nx">StopIteration</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// This works because:</span>
<span class="nx">StopIteration</span> <span class="k">instanceof</span> <span class="nx">StopIteration</span> <span class="o">===</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">}</span>
</pre></div></figure>
<p>As <em>StopIteration</em> is a singleton of type <em>StopIteration</em> you can also catch it
by checking for equality:</p>
<figure class='code'> <div class="highlight"><pre><span class="k">try</span> <span class="p">{</span>
<span class="k">throw</span> <span class="nx">StopIteration</span><span class="p">;</span>
<span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">e</span> <span class="k">if</span> <span class="nx">e</span> <span class="o">===</span> <span class="nx">StopIteration</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// ... handle exception</span>
<span class="p">}</span>
</pre></div></figure>
<h2>StopIteration is mutable</h2>
<p>You should be aware that <em>StopIteration</em> is a mutable global. Just like
<em>undefined</em> it can be modified to hold any other value. If you write a library
and want to shield against modifications from outside you can use this neat
little trick I found on
<a href="http://calculist.blogspot.de/2008/04/how-to-spell-stopiteration.html">Dave Herman’s blog</a>:</p>
<figure class='code'> <div class="highlight"><pre><span class="p">(</span><span class="kd">function</span><span class="p">(){</span><span class="k">try</span><span class="p">{(</span><span class="kd">function</span><span class="p">(){</span><span class="kc">true</span><span class="o">||</span><span class="p">(</span><span class="k">yield</span><span class="p">)})().</span><span class="nx">next</span><span class="p">()}</span><span class="k">catch</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span><span class="k">return</span> <span class="nx">e</span><span class="p">}})()</span>
</pre></div></figure>
<p>The inner function is a generator that terminates immediately and therefore will
throw a <em>StopIteration</em>. The outer function simply catches and returns it.</p>
<h2>StopIteration may become a constructor</h2>
<p>The current
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:iterators#stopiteration">iterator strawman</a>
states that <em>StopIteration</em> will become a constructor to maintain compatibility
with generator functions returning values.</p>
<figure class='code'> <div class="highlight"><pre><span class="nx">Iter</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">next</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">cur</span> <span class="o"><</span> <span class="k">this</span><span class="p">.</span><span class="nx">max</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">cur</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">var</span> <span class="nx">stop</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">StopIteration</span><span class="p">();</span>
<span class="nx">stop</span><span class="p">.</span><span class="nx">value</span> <span class="o">=</span> <span class="s2">"sequence exhausted"</span><span class="p">;</span>
<span class="k">throw</span> <span class="nx">stop</span><span class="p">;</span>
<span class="p">};</span>
</pre></div></figure>
<p>The equality check from above would not work anymore so it might be better to
just use <em>instanceof</em>.</p>
<h2>StopIteration may not be part of ES6</h2>
<p>The Python way of throwing to denote the end of a sequence is backwards
compatible with old ECMAScript versions but there seem to be
<a href="https://mail.mozilla.org/pipermail/es-discuss/2013-February/028668.html">people</a>
<a href="https://mail.mozilla.org/pipermail/es-discuss/2013-March/028937.html">not happy</a>
<a href="http://esdiscuss.org/notes/2013-03-12">with the current proposal</a>.
While I can’t tell whether <em>StopIteration</em> is really to be removed a couple of
alternative suggestions have been made:</p>
<h3>Introduce a keyword to end a frame</h3>
<p>To not misuse exceptions for normal control flow ES6 could introduce a
<em>stopiteration</em> or <em>endframe</em> keyword that would end the current frame with
an optional return value. The obvious downside is that it is probably not
backwards compatible.</p>
<figure class='code'> <div class="highlight"><pre><span class="nx">Iter</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">next</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">cur</span> <span class="o"><</span> <span class="k">this</span><span class="p">.</span><span class="nx">max</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">cur</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">stopiteration</span> <span class="p">[</span><span class="nx">reason</span><span class="p">];</span>
<span class="c1">// or endframe [reason];</span>
<span class="p">};</span>
</pre></div></figure>
<h3>Add an iterator.hasNext() method</h3>
<p>Just like Java the iterator API could consist of the two methods <em>next()</em> and
<em>hasNext()</em>. The client would then need to check <em>hasNext()</em> every time before
calling <em>next()</em>.</p>
<figure class='code'> <div class="highlight"><pre><span class="nx">Iter</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="p">{</span>
<span class="nx">hasNext</span><span class="o">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">cur</span> <span class="o"><</span> <span class="k">this</span><span class="p">.</span><span class="nx">max</span><span class="p">;</span>
<span class="p">},</span>
<span class="nx">next</span><span class="o">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">hasNext</span><span class="p">())</span> <span class="p">{</span>
<span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">cur</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s2">"sequence exhausted"</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">};</span>
</pre></div></figure>
<h3>Let next() always return an object</h3>
<p>Custom iterators would be required to implement a single method but would not
need to throw. Instead they would return an object with the property <em>done</em> set
to true to indicate that the sequence has ended. The <em>value</em> property would be
used to store values passed to <em>yield</em> or <em>return</em> in a generator function.</p>
<figure class='code'> <div class="highlight"><pre><span class="p">{</span>
<span class="nx">next</span><span class="p">()</span> <span class="o">-></span> <span class="p">{</span> <span class="nx">done</span><span class="o">:</span> <span class="kc">false</span> <span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="nx">any</span> <span class="p">}</span>
<span class="o">|</span> <span class="p">{</span> <span class="nx">done</span><span class="o">:</span> <span class="kc">true</span><span class="p">[,</span> <span class="nx">value</span><span class="o">:</span> <span class="nx">any</span><span class="p">]</span> <span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<h3>Food for thought</h3>
<p>This is in no way a complete list of possibilities or proposals that were
brought up on <a href="http://mail.mozilla.org/pipermail/es-discuss/">es-discuss</a> so
please make up your own mind about the current iterators implementation and the
suggested improvements.</p>
<h2>The future is bright</h2>
<p>Whether or not <em>StopIteration</em> will end up in ES6, generators and iterators are
great and you should make sure to be prepared when they become available in
modern browsers as well as on Node.js.</p>
<p>I concentrated particularly on <em>StopIteration</em> but there are
<a href="http://jlongster.com/2012/10/05/javascript-yield.html">lots of</a>
<a href="http://ejohn.org/blog/javascript-18-progress/">great</a>
<a href="http://bjouhier.wordpress.com/2012/05/18/asynchronous-javascript-with-generators-an-experiment/">posts</a>
out there that go way more into depth about generators and their usage. Make
sure to also take a look at libraries like <a href="http://taskjs.org/">Task.js</a> that
combines generators with promises to cooperative tasks.</p>
</article>
<article class="post">
<header class="article-header">
<h1><a href="/blog/2013/02/getusermedia-part-3-simple-motion-detection-in-a-live-video/" title="getUserMedia() part 3: simple motion detection in a live video">getUserMedia() part 3: simple motion detection in a live video</a></h1>
<time datetime="2013-02-27T12:00:00+01:00" pubdate data-updated="true">February, 27<span>th</span> 2013</time>
</header>
<p>Now that you should already know how to build a
<a href="/blog/2012/10/building-a-live-green-screen-with-getusermedia-and-mediastreams/">live green screen</a>
and an
<a href="/blog/2012/10/getusermedia-part-2-building-an-eyetoy-like-mini-game/">EyeToy-like mini-game</a>
using nothing but plain JavaScript and a modern browser supporting WebRTC, let
us move on to another interesting example: simple motion detection in a live
video.</p>
<h2>The initialization code</h2>
<p>To detect motion in a video we need to compare at least two frames. We will use
<a href="https://developer.mozilla.org/en-US/docs/JavaScript_typed_arrays">typed arrays</a>
to store the lightness data of the previous frames:</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">initialize</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// ... code to initialize the canvas and video elements ...</span>
<span class="c1">// Prepare buffers to store lightness data.</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</span> <span class="mi">2</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">buffers</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="k">new</span> <span class="nx">Uint8Array</span><span class="p">(</span><span class="nx">width</span> <span class="o">*</span> <span class="nx">height</span><span class="p">));</span>
<span class="p">}</span>
<span class="c1">// Get the webcam's stream.</span>
<span class="nx">nav</span><span class="p">.</span><span class="nx">getUserMedia</span><span class="p">({</span><span class="nx">video</span><span class="o">:</span> <span class="kc">true</span><span class="p">},</span> <span class="nx">startStream</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{});</span>
<span class="p">}</span>
</pre></div></figure>
<p>We want two frame buffers - a single one results in a heavily
flickering motion video but the more frames we store the more motion blur
we will see. Two seems like a good value for demonstration purposes.</p>
<h2>Illustrating lightness changes</h2>
<p>The main <em>draw()</em> function from
<a href="/blog/2012/10/building-a-live-green-screen-with-getusermedia-and-mediastreams/">part 1</a>
did not change except that we now call <em>markLightnessChanges()</em> for every frame.
This is also the probably most interesting function of the whole demo:</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">markLightnessChanges</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// Pick the next buffer (round-robin).</span>
<span class="kd">var</span> <span class="nx">buffer</span> <span class="o">=</span> <span class="nx">buffers</span><span class="p">[</span><span class="nx">bufidx</span><span class="o">++</span> <span class="o">%</span> <span class="nx">buffers</span><span class="p">.</span><span class="nx">length</span><span class="p">];</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="nx">j</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</span> <span class="nx">buffer</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">,</span> <span class="nx">j</span> <span class="o">+=</span> <span class="mi">4</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// Determine lightness value.</span>
<span class="kd">var</span> <span class="nx">current</span> <span class="o">=</span> <span class="nx">lightnessValue</span><span class="p">(</span><span class="nx">data</span><span class="p">[</span><span class="nx">j</span><span class="p">],</span> <span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">1</span><span class="p">],</span> <span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">2</span><span class="p">]);</span>
<span class="c1">// Set color to black.</span>
<span class="nx">data</span><span class="p">[</span><span class="nx">j</span><span class="p">]</span> <span class="o">=</span> <span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="c1">// Full opacity for changes.</span>
<span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="mi">255</span> <span class="o">*</span> <span class="nx">lightnessHasChanged</span><span class="p">(</span><span class="nx">i</span><span class="p">,</span> <span class="nx">current</span><span class="p">);</span>
<span class="c1">// Store current lightness value.</span>
<span class="nx">buffer</span><span class="p">[</span><span class="nx">i</span><span class="p">]</span> <span class="o">=</span> <span class="nx">current</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<p>We determine the lightness value of every pixel in the canvas and compare it
to its values in the previously captured frames. If the difference to one of
those buffers exceeds a specific threshold the pixel will be black, if not it
becomes transparent.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">lightnessHasChanged</span><span class="p">(</span><span class="nx">index</span><span class="p">,</span> <span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">buffers</span><span class="p">.</span><span class="nx">some</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">buffer</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">abs</span><span class="p">(</span><span class="nx">value</span> <span class="o">-</span> <span class="nx">buffer</span><span class="p">[</span><span class="nx">index</span><span class="p">])</span> <span class="o">>=</span> <span class="mi">15</span><span class="p">;</span>
<span class="p">});</span>
<span class="p">}</span>
</pre></div></figure>
<h2>Blend mode difference</h2>
<p>The simple method we use to detect motion is called a
<a href="http://en.wikipedia.org/wiki/Blend_modes#Difference">blend mode difference</a>.
That is a quite fancy word to say: we compare two images (also called layers
or frames) by putting them on top of each other and subtracting the bottom from
the top layer. In this example we do it for every pixel’s L-value of the
<a href="https://en.wikipedia.org/wiki/HSL_and_HSV">HSL color model</a>.</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">lightnessValue</span><span class="p">(</span><span class="nx">r</span><span class="p">,</span> <span class="nx">g</span><span class="p">,</span> <span class="nx">b</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">min</span><span class="p">(</span><span class="nx">r</span><span class="p">,</span> <span class="nx">g</span><span class="p">,</span> <span class="nx">b</span><span class="p">)</span> <span class="o">+</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">max</span><span class="p">(</span><span class="nx">r</span><span class="p">,</span> <span class="nx">g</span><span class="p">,</span> <span class="nx">b</span><span class="p">))</span> <span class="o">/</span> <span class="mi">255</span> <span class="o">*</span> <span class="mi">50</span><span class="p">;</span>
<span class="p">}</span>
</pre></div></figure>
<p>If the current frame is identical to the previous one, the lightness
difference will be exactly zero for all pixels. If the frames differ because
something in that picture has moved then there is a good chance that lightness
values change where motion occured. A small threshold ensures that we ignore
noise in the signal.</p>
<h2>Demo and screencast</h2>
<p>That is all! Take a look at the <a href="/demos/motion-detection/">live demo</a> or watch
the screencast below:</p>
<iframe class="embed embed-space"
src="http://player.vimeo.com/video/60650211?title=1&byline=1&portrait=1"
width="500" height="195" frameborder="0"
webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
<p>You can create some really great demos with this simple technique. Here is a
neat one of
<a href="http://www.soundstep.com/blog/experiments/jsdetection/">a xylophone you can play by waving your hands</a>
(which unfortunately does not work in Firefox).</p>
<p>Whatever your ideas may be, I encourage you to fiddle around with the small
demos I provided in my three getUserMedia() examples so far and let me know if
you built something amazing!</p>
</article>
<article class="post">
<header class="article-header">
<h1><a href="/blog/2013/02/note-to-myself-dont-be-lazy/" title="Note to myself: Don't be lazy">Note to myself: Don’t be lazy</a></h1>
<time datetime="2013-02-25T12:00:00+01:00" pubdate data-updated="true">February, 25<span>th</span> 2013</time>
</header>
<p>Back in October 2012 I wrote two blog posts,
<a href="/blog/2012/10/building-a-live-green-screen-with-getusermedia-and-mediastreams/">getUserMedia part 1</a>
and <a href="/blog/2012/10/getusermedia-part-2-building-an-eyetoy-like-mini-game/">part 2</a>,
including demos which unfortunately would run in Firefox, only. I did not
explicitly want to be exclusive but I think I just did not feel like looking up
why my code did not work in Opera and why exactly webkitGetUserMedia() behaved
differently than mozGetUserMedia(). I was being lazy.</p>
<p>I also intended to mix in a couple of nice JavaScript features, like
block-scoped variable definitions with
<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/let">let</a>,
<a href="https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7">destructuring assignments</a>
or <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Set">Sets</a>
(did I just do it again?). In hindsight this does not really make sense as I
should not expect visitors to want to learn about cutting-edge JavaScript
features when viewing a getUserMedia() post.</p>
<p>Before finishing my third piece on getUserMedia() I decided to update the demos
of my older posts to run in any modern browser. I also seized the chance to
overhaul code examples which did not adhere to my coding standards anymore.</p>
<p>If you should ever be in a similar situation - please take a couple of minutes
to write code that runs in all modern browsers so people can enjoy your demos in
their browser of choice. Please don’t be lazy.</p>
</article>
<article class="post">
<header class="article-header">
<h1><a href="/blog/2012/10/getusermedia-part-2-building-an-eyetoy-like-mini-game/" title="getUserMedia() part 2: building an EyeToy-like mini-game">getUserMedia() part 2: building an EyeToy-like mini-game</a></h1>
<time datetime="2012-10-18T22:00:00+02:00" pubdate data-updated="true">October, 18<span>th</span> 2012</time>
</header>
<p>This post is a follow-up to my previous one about
<a href="/blog/2012/10/building-a-live-green-screen-with-getusermedia-and-mediastreams/">building a live green screen with getUserMedia() and MediaStreams</a>.
If you have not read it yet, this might be a good time. We will extend the small
example to build an EyeToy-like mini-game.</p>
<h2>Some additions</h2>
<figure class='code'> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">video</span><span class="p">,</span> <span class="nx">width</span><span class="p">,</span> <span class="nx">height</span><span class="p">,</span> <span class="nx">context</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">revealed</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="kc">null</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">initialize</span><span class="p">()</span> <span class="p">{</span>
</pre></div></figure>
<p>First, we will add a variable called <em>revealed</em> that keeps track of all pixels
that have already been revealed by holding a green object in front of the
camera. Instead of <em>replaceGreen()</em> we will call our method <em>revealGreen()</em>
from now on:</p>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">revealGreen</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">len</span> <span class="o">=</span> <span class="nx">width</span> <span class="o">*</span> <span class="nx">height</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="nx">j</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</span> <span class="nx">len</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">,</span> <span class="nx">j</span> <span class="o">+=</span> <span class="mi">4</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// This pixel has already been revealed.</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">i</span> <span class="k">in</span> <span class="nx">revealed</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">continue</span><span class="p">;</span>
<span class="p">}</span>
</pre></div></figure>
<p>When iterating over all of the canvas’ pixels we check whether the current index
is marked as revealed. If so we do not need to check its color but set its
opacity to zero and continue with the next iteration.</p>
<figure class='code'> <div class="highlight"><pre> <span class="c1">// Convert from RGB to HSL...</span>
<span class="kd">var</span> <span class="nx">hsl</span> <span class="o">=</span> <span class="nx">rgb2hsl</span><span class="p">(</span><span class="nx">data</span><span class="p">[</span><span class="nx">j</span><span class="p">],</span> <span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">1</span><span class="p">],</span> <span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">2</span><span class="p">]);</span>
<span class="kd">var</span> <span class="nx">h</span> <span class="o">=</span> <span class="nx">hsl</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="nx">s</span> <span class="o">=</span> <span class="nx">hsl</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="nx">l</span> <span class="o">=</span> <span class="nx">hsl</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span>
<span class="c1">// ... and check if we have a somewhat green pixel.</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">h</span> <span class="o">>=</span> <span class="mi">90</span> <span class="o">&&</span> <span class="nx">h</span> <span class="o"><=</span> <span class="mi">160</span> <span class="o">&&</span> <span class="nx">s</span> <span class="o">>=</span> <span class="mi">25</span> <span class="o">&&</span> <span class="nx">s</span> <span class="o"><=</span> <span class="mi">90</span> <span class="o">&&</span> <span class="nx">l</span> <span class="o">>=</span> <span class="mi">20</span> <span class="o">&&</span> <span class="nx">l</span> <span class="o"><=</span> <span class="mi">75</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">data</span><span class="p">[</span><span class="nx">j</span> <span class="o">+</span> <span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="nx">revealed</span><span class="p">[</span><span class="nx">i</span><span class="p">]</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div></figure>
<p>If the pixel has not been revealed yet but is a green one, we make it
transparent like before and mark it to stay that way.</p>
<h2>Demo and screencast</h2>
<p>That is all! Take a look at the <a href="/demos/eye-toy/">live demo</a> or watch the
screencast below:</p>
<iframe class="embed"
src="http://player.vimeo.com/video/51703468?title=1&byline=1&portrait=1"
width="500" height="195" frameborder="0"
webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
<h2>I know…</h2>
<p>… this is not much of a game but rather a small demo one could turn into a
mini-game with little effort. Play around with the code and see what you can
come up with!</p>
</article>
<article class="post">
<header class="article-header">
<h1><a href="/blog/2012/10/building-a-live-green-screen-with-getusermedia-and-mediastreams/" title="Building a live green screen with getUserMedia() and MediaStreams">Building a live green screen with getUserMedia() and MediaStreams</a></h1>
<time datetime="2012-10-17T20:00:00+02:00" pubdate data-updated="true">October, 17<span>th</span> 2012</time>
</header>
<p>While recently watching a talk about the new WebRTC features I was reminded of
Paul Rouget’s great
<a href="https://developer.mozilla.org/samples/video/chroma-key/index.xhtml">green screen demo</a>
and thought that this would be a cool thing to have for live video as well.
Let us build a live green screen!</p>
<h2>The markup</h2>
<figure class='code'> <div class="highlight"><pre><span class="nt"><body></span>
<span class="nt"><video</span> <span class="na">id=</span><span class="s">"v"</span> <span class="na">width=</span><span class="s">"320"</span> <span class="na">height=</span><span class="s">"240"</span><span class="nt">></video></span>
<span class="nt"><canvas</span> <span class="na">id=</span><span class="s">"c"</span> <span class="na">width=</span><span class="s">"320"</span> <span class="na">height=</span><span class="s">"240"</span><span class="nt">></canvas></span>
<span class="nt"></body></span>
</pre></div></figure>
<p>Those are the parts we need. A <video> element that plays the media stream
and a canvas we will use to read and transform image data.</p>
<h2>The JavaScript</h2>
<figure class='code'> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">initialize</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// Get the webcam's stream.</span>
<span class="nx">navigator</span><span class="p">.</span><span class="nx">getUserMedia</span><span class="p">({</span><span class="nx">video</span><span class="o">:</span> <span class="kc">true</span><span class="p">},</span> <span class="nx">startStream</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{});</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">startStream</span><span class="p">(</span><span class="nx">stream</span><span class="p">)</span> <span class="p">{</span>