-
Notifications
You must be signed in to change notification settings - Fork 0
/
Secrets_of_the_JS_Ninja.mm
1196 lines (1100 loc) · 22.5 KB
/
Secrets_of_the_JS_Ninja.mm
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
<map version="0.9.0">
<!-- To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net -->
<node CREATED="1392477834070" ID="ID_730209379" MODIFIED="1392477848485" TEXT="Secrets of the JS Ninja">
<node CREATED="1392477871547" ID="ID_288695224" MODIFIED="1393725171632" POSITION="right" TEXT="2. Functions">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
JS is a functional language.
</p>
<p>
We can create anonymous function at any time.
</p>
<p>
They can be passed as values to other functions and so on.
</p>
<p>
*/
</p>
</body>
</html>
</richcontent>
<node CREATED="1392477915386" ID="ID_1823430122" MODIFIED="1392589912872" TEXT="1. Function Definition">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
There're different possible ways to define a function:
</p>
<p>
</p>
<p>
Traditional way:
</p>
<p>
*/
</p>
<p>
</p>
<p>
function getTrue() {return true;}
</p>
<p>
</p>
<p>
/**
</p>
<p>
or using anonymous functions:
</p>
<p>
*/
</p>
<p>
</p>
<p>
var iSee = function() {return true;};
</p>
<p>
</p>
<p>
boxOfMatches.isSmall = function() {return true;};
</p>
<p>
</p>
<p>
assert (getTrue() && iSee() && boxOfMatches(), "All are functions that return true value.")
</p>
<p>
</p>
<p>
/**
</p>
<p>
If we'd define the getTrue function after the assertion, it'd work too, because no matter where the function is defined (within the current scope) it's visible and accessible. For instance:
</p>
<p>
*/
</p>
<p>
</p>
<p>
function orderDefinitionCheck() {
</p>
<p>
    var ret = check() == check();
</p>
<p>
    return assert( ret, "We can't get below this line due to the return statement, but it never mind, the check function is available ....");
</p>
<p>
    function check() { return true;}
</p>
<p>
}
</p>
<p>
</p>
<p>
orderDefinitionCheck();
</p>
<p>
</p>
<p>
/**
</p>
<p>
Above is true only for traditionally defined functions,  anonymous functions exists only after the point at which they've been defined.
</p>
<p>
*/
</p>
<p>
</p>
</body>
</html></richcontent>
</node>
<node CREATED="1392483721646" ID="ID_736136469" MODIFIED="1392589895707" TEXT="2. Anonymous Functions and Recursion">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
Recursion with named function is simple:
</p>
<p>
*/
</p>
<p>
</p>
<p>
function hiya(n) {
</p>
<p>
    return n > 0 ? hiya(n - 1) + 'a' : 'hiy';
</p>
<p>
}
</p>
<p>
</p>
<p>
assert(hiya(4) == 'hiyaaaa', 'No problem here.');
</p>
<p>
</p>
<p>
/**
</p>
<p>
It's the same with anonymous function within the object:
</p>
<p>
*/
</p>
<p>
var ninja = {
</p>
<p>
    hiya: function(n) {
</p>
<p>
        return n > 0 ? hiya(n - 1) + 'a' : 'hiy';
</p>
<p>
    }
</p>
<p>
};
</p>
<p>
</p>
<p>
assert(ninja.hiya(4) == 'hiyaaaa', 'Nor here.');
</p>
<p>
</p>
<p>
/**
</p>
<p>
But when we try to create a new samurai from the ninja object, anonymous function hiya will stil reference the ninja object and when we re-define it, it'll get lost.
</p>
<p>
*/
</p>
<p>
</p>
<p>
var samurai = {hiya: ninja.hiya};
</p>
<p>
var ninja = {}; // We've lost the hiya function here.
</p>
<p>
</p>
<p>
try {
</p>
<p>
    samurai.hiya(4);
</p>
<p>
} catch(e) {
</p>
<p>
    assert(true, 'Right samurai does not yell even.');
</p>
<p>
}
</p>
<p>
</p>
<p>
/**
</p>
<p>
This can be solved by giving the anonymous function a name ...
</p>
<p>
*/
</p>
<p>
</p>
<p>
var ninja = {
</p>
<p>
    hiya: function hiya(n) {
</p>
<p>
        return (n > 0 ? hiya(n -1) + 'a': 'hiy');
</p>
<p>
    }
</p>
<p>
}
</p>
<p>
</p>
<p>
assert (ninja.hiya(4) == 'hiyaaaa', 'Ninja yells for exact time - 4 a\'s.');
</p>
<p>
</p>
<p>
var samurai = {hiya: ninja.hiya};
</p>
<p>
var ninja = {}; // Wipe out the ninja.
</p>
<p>
</p>
<p>
assert (samurai.hiya(4) == 'hiyaaaa', 'Samurai can also yell for the exact time.');
</p>
<p>
</p>
<p>
/**
</p>
<p>
This ability: naming anonymous function extends even further. It can be done in normal variable assignments, but there're consequences ...
</p>
<p>
*/
</p>
<p>
</p>
<p>
var ninja = function innerNinja() {
</p>
<p>
    assert(ninja == innerNinja, 'This function has two names at once!');
</p>
<p>
};
</p>
<p>
</p>
<p>
ninja();
</p>
<p>
assert(typeof innerNinja == 'undefined', 'But innerNinja is not defined outside the function');
</p>
<p>
</p>
<p>
/**
</p>
<p>
So the most important point is: <b>Anonymous functions can be named, but those names are only visible within the functions themselves. </b>
</p>
<p>
</p>
<p>
Giving names to anonymous functions can provide clarity and simplicity, but the naming process is an extra step that we need to take to achieve that.
</p>
<p>
</p>
<p>
We can circumvent that entirely by using the <b>callee</b> property of the <b>arguments</b>  object.
</p>
<p>
*/
</p>
<p>
</p>
<p>
var ninja = {
</p>
<p>
    hiya: function(n) {
</p>
<p>
        return (n>0 ? arguments.callee(n-1) + 'a': 'hiy');
</p>
<p>
    }
</p>
<p>
}
</p>
<p>
</p>
<p>
assert(ninja.hiya(4) == 'hiyaaaa', 'arguments.callee is the function itself.');
</p>
<p>
</p>
<p>
/**
</p>
<p>
Arguments.callee is available within every function (named or not) and can server as reliable way to access the function itself.
</p>
<p>
*/
</p>
</body>
</html></richcontent>
</node>
<node CREATED="1392589897251" ID="ID_206511117" MODIFIED="1392762544725" TEXT="3. Functions as Objects">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
Functions behave like objects - can have properties, prototype, .... and what more: they're callable!
</p>
<p>
*/
</p>
<p>
</p>
<p>
var obj = {};
</p>
<p>
var fn = function(){}; // Note the semicolon after the function definition - it's a <b>good practice</b>.
</p>
<p>
assert(obj && fn "Both exist.");
</p>
<p>
</p>
<p>
obj.prop = "some value";
</p>
<p>
fn.prop = "some value";
</p>
<p>
assert(obj.prop == fn.prop, "Both are objects, both have the property.")
</p>
<p>
</p>
</body>
</html></richcontent>
<node CREATED="1392676370919" ID="ID_1555702069" MODIFIED="1392758801392" TEXT="3.1. Storing Functions">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
Storing UNIQUE functions within a structure (by their uniqueness ;)).
</p>
<p>
*/
</p>
<p>
</p>
<p>
var store =  {
</p>
<p>
id: 1,
</p>
<p>
cache: {},
</p>
<p>
add: function(fn) {
</p>
<p>
if (!fn.id) {
</p>
<p>
fn.id = store.id++;
</p>
<p>
return !!(store.cache[fn.id] = fn); // !! turns following expression to its boolean equivalent
</p>
<p>
}
</p>
<p>
}
</p>
<p>
};
</p>
<p>
</p>
<p>
function ninja(){
</p>
<p>
log(ninja.id);
</p>
<p>
};
</p>
<p>
</p>
<p>
function samurai() {
</p>
<p>
log(samurai.id);
</p>
<p>
};
</p>
<p>
</p>
<p>
assert(store.add(ninja), "ninja came.");
</p>
<p>
assert(!store.add(ninja), "ninja came before.");
</p>
<p>
</p>
<p>
ninja();
</p>
<p>
</p>
<p>
assert(store.add(samurai), "samurai came.");
</p>
<p>
assert(!store.add(ninja) , "ninja came before.");
</p>
<p>
assert(!store.add(samurai), "samurai came before.");
</p>
<p>
</p>
<p>
samurai();
</p>
<p>
</p>
</body>
</html></richcontent>
</node>
<node CREATED="1392758803256" ID="ID_1930146017" MODIFIED="1392841478424" TEXT="3.2. Self Memoizing Functions">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
Well, he says poorly written algorithm for computing primes.
</p>
<p>
Let's make it a bit better by searching only to the rounded half of the given number with added answers cache.
</p>
<p>
*/
</p>
<p>
</p>
<p>
function isPrime(num) {
</p>
<p>
</p>
<p>
    if (isPrime.cache[num] != null) {
</p>
<p>
        return isPrime.cache[num];
</p>
<p>
    }
</p>
<p>
</p>
<p>
  var answer = true;
</p>
<p>
    if (1 < num && num < 4) {
</p>
<p>
  answer = true;
</p>
<p>
    } else if (num % 2 == 0) {
</p>
<p>
   answer = false;
</p>
<p>
    } else {
</p>
<p>
        var half = Math.round(num / 2);
</p>
<p>
        for (var i = half; i > 3; i--) {
</p>
<p>
            if (num % i == 0) {
</p>
<p>
  answer = false;
</p>
<p>
               
</p>
<p>
                break;
</p>
<p>
            }
</p>
<p>
        }
</p>
<p>
    }
</p>
<p>
   
</p>
<p>
    return isPrime.cache[num] = answer;
</p>
<p>
}
</p>
<p>
;
</p>
<p>
</p>
<p>
isPrime.cache = {}; // !!! this is important line
</p>
<p>
</p>
<p>
var lastI = 251;
</p>
<p>
for (var i = 251; i < 501; i=i+2) {
</p>
<p>
    assert(isPrime(i), i + " is prime.");
</p>
<p>
    assert(isPrime.cache[lastI], (lastI) + " is cached ...");
</p>
<p>
    var lastI = i;
</p>
<p>
}
</p>
<p>
</p>
<p>
/**
</p>
<p>
A modern example for this is querying for a set if DOM elements by name ...
</p>
<p>
*/
</p>
<p>
</p>
<p>
function getElements(name) {
</p>
<p>
    return getElements.cache[ name ] = getElements.cache[ name ] ||
</p>
<p>
            document.getElementsByTagName(name);
</p>
<p>
}
</p>
<p>
getElements.cache = {}
</p>
<p>
</p>
<p>
/**
</p>
<p>
It's quite simple and yields 7x performance increase!!
</p>
<p>
*/
</p>
</body>
</html></richcontent>
</node>
</node>
<node CREATED="1392762532363" ID="ID_684269010" MODIFIED="1393721767893" TEXT="4. Context">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
<u><b>V</b>ery <b>I</b>mportant <b>F</b>eature </u>
</p>
<p>
</p>
<p>
most poverful and also confusing
</p>
<p>
</p>
<p>
The context represents: <b>The object within which function is being executed.</b> 
</p>
<p>
</p>
<p>
E.g: defining a function within an object structure will ensure that its context always refers to that object (unless otherwise overwritten)
</p>
<p>
*/
</p>
<p>
</p>
<p>
var katana = {
</p>
<p>
    isSharp: true,
</p>
<p>
    use:function () {
</p>
<p>
        this.isSharp = !!this.isSharp; // remember that boolean cast
</p>
<p>
    }
</p>
<p>
};
</p>
<p>
</p>
<p>
katana.use();
</p>
<p>
assert( !katana.isSharp, "Verify katana has been used.");
</p>
<p>
</p>
<p>
/**
</p>
<p>
What if function is not explicitly declared as a property of an object? Then its context refers to the global object.
</p>
<p>
*/
</p>
<p>
</p>
<p>
function katana() {
</p>
<p>
    this.isSharp = true;
</p>
<p>
}
</p>
<p>
</p>
<p>
katana();
</p>
<p>
assert( isSharp === true, "A global object now exists with such name and value.");
</p>
<p>
</p>
<p>
var shuriken = {
</p>
<p>
    toss: function() {
</p>
<p>
        this.isSharp = true;
</p>
<p>
    }
</p>
<p>
};
</p>
<p>
</p>
<p>
shuriken.toss();
</p>
<p>
assert( shuriken.isSharp === true, "When it's an object property, value is set within its context." );
</p>
<p>
</p>
<p>
/**
</p>
<p>
All of this becomes <b>QUITE IMPORTANT</b> when dealing with functions in a variety of contexts - knowing the contexts affects the result of the code.
</p>
<p>
</p>
<p>
Note: In ECMAScript4 (JavaScript 2) function defined within an other function will inherit the context of the outer function.
</p>
<p>
*/
</p>
<p>
</p>
<p>
/**
</p>
<p>
And now for something completely different.
</p>
<p>
</p>
<p>
It's time to explore the most complex contex usage: The fact that <b>a function context can be redefined anytime that it's called</b>.
</p>
<p>
</p>
<p>
Javascript provides methods: <b>call</b> and <b>apply</b> (on every function) that can be used to
</p>
<p>
</p>
<p>
- call the function
</p>
<p>
- define its context
</p>
<p>
- specify its incoming arguments
</p>
<p>
</p>
<p>
*/
</p>
<p>
</p>
<p>
var object = {};
</p>
<p>
function fn() {
</p>
<p>
    return this;
</p>
<p>
}
</p>
<p>
</p>
<p>
assert( fn() == this, "The context is the global object." );
</p>
<p>
assert ( fn.call(object) == object, "The context is a specific object.");
</p>
<p>
</p>
<p>
/**
</p>
<p>
These two functions differ in a way they set incoming arguments:
</p>
<p>
</p>
<p>
- .call() passes in arguments individually
</p>
<p>
- .apply() passes in arguments as an array
</p>
<p>
*/
</p>
<p>
</p>
<p>
function add(a, b) {
</p>
<p>
    return a + b;
</p>
<p>
}
</p>
<p>
assert(add.call(this, 1, 2) == 3, ".call() with individual arguments");
</p>
<p>
assert(add.apply(this, [1, 2]) == 3, ".apply() takes and array of arguments");
</p>
</body>
</html>
</richcontent>
<node CREATED="1393721770343" ID="ID_1215580485" MODIFIED="1393723507735" TEXT="4.1 Looping">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
/**
</p>
<p>
Example of using .call() to make an array looping function with a callback - frequent addition to most JavaScript libraries. The result simplifies the process of looping through an array.
</p>
<p>
*/
</p>
<p>
</p>
<p>
function loop(array, fn) {
</p>
<p>
    for (var i = 0; i < array.length, i++) {
</p>
<p>
        fn.call(array, array[i], i);
</p>
<p>
    }
</p>
<p>
}
</p>
<p>
</p>
<p>
var num = 0;
</p>
<p>