-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.html
More file actions
1983 lines (1557 loc) · 68.6 KB
/
index.html
File metadata and controls
1983 lines (1557 loc) · 68.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<!-- Copyright Guillaume Lathoud 2016
Boost License: see the file ./LICENSE
-->
<html>
<head>
<meta charset=utf-8/>
<title>transfun</title>
<style type="text/css">
body { font-family: helvetica;
text-align: justify;
font-family: Verdana,Arial,'Lucida Grande',Sans-Serif;
}
.highlight { margin-top: 2em; text-decoration: underline; }
.highlight-anchor { visibility: hidden; }
.highlight:hover .highlight-anchor { visibility: visible; }
.left { float : left; }
.right { float : right; }
.clear { clear: both; }
code { font-size: 1.1em; }
dd { margin-bottom: 1em; }
.legend { font-weight: bold; text-align: center; margin-bottom: 1.5em; margin-top: 0.35em; font-style: italic; }
.centered-pic { text-align: center; margin-top: 3em; margin-bottom: 2em; }
.centered-cell { text-align: center; vertical-align: middle; padding-left: 1.75em; padding-right: 0;}
.yes-no img { max-width : 1.25em; }
.done { text-decoration: line-through; }
#title { margin-bottom: 6em; }
.section-hr, .section-title {margin-top: 2.5em; }
.email_icon { vertical-align: middle; max-height: 2.25em; }
@media only print { .print-hidden, .section-anchor, .highlight-anchor { visibility: hidden; } }
.license { width: 110%; height: 400px; border: none; margin: 0; paddin: 0; overflow: hidden; }
.left, .right { padding-left: 2em; padding-right: 2em; }
@media screen and (max-width: 999px) {
pre, .left, .right { font-size: 1.6em; }
.mobile-spread-img { width: 100%; }
}
@media screen and (min-width: 1000px) {
body { max-width: 600px; margin: auto;
line-height: 1.5em;
}
}
</style>
<link rel="stylesheet" type="text/css" href="rsrc_web/prettify/prettify.css"/>
<script type="text/javascript" src="transfun.js"></script>
<script type="text/javascript" src="rsrc_web/opinel.js"></script>
</head>
<body>
<script type="text/javascript">
(function () {
var c_transfun = hh.code( 'transfun.js' )
, c_appfun = hh.code( 'appfun' )
, c_arr = hh.code( 'arr' )
, c_lazy = hh.code( 'lazy.js' )
, c_m = hh.code( 'map' )
, c_mfr = hh.code( 'map/filter/reduce' )
, c_mfr_etc = hh.code( 'map, filter, reduce, redinit, and, or' )
, c_mfr_etc_in = hh.code( 'mapIn, filterIn, reduceIn, redinitIn, andIn, orIn ' )
, c_mfr_etc_right = hh.code( 'mapRight, filterRight, reduceRight, redinitRight, andRight, orRight' )
, c_o2arr_conv = hh.code( 'o2values, o2keys, keys2o' ) + ' and ' + hh.code( 'o2kv, kv2o' )
, c_current = hh.code( 'current' )
, c_arg = hh.code( 'arg' )
, c_range_direct = hh.code( 'range' )
, c_range_of = hh.code( 'rangeOf' )
, c_range = c_range_direct + ' & ' + c_range_of
, c_next = hh.code( 'next' )
, c_parallel = hh.code( 'parallel.js' )
, c_tval = hh.code( 'tval' )
, c_bind = hh.code( 'bind' )
, c_wu = hh.code( 'wu.js' )
, github_ref = 'http://github.com/glathoud/transfun'
, haskell_ref = 'http://chrisdone.com/posts/stream-composability' // 'https://www.reddit.com/r/programming/comments/2s5gj2/java_8_no_more_loops/cnn30vn'
, lazy_ref = 'https://github.com/dtao/lazy.js/'
, nokeyorder_ref = 'http://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties'
, parallel_ref = 'https://github.com/glathoud/transfun/blob/master/plugin/parallel.js'
, parallel_example_ref = 'test.html#async-unit-test'
, transducers_js_ref = 'https://www.reddit.com/r/javascript/comments/42sxfb/understanding_transducers_in_javascript/'
, jsperf_motivation = 'http://jsperf.com/arr-map-filter-reduce/4'
, test_ref = 'test.html'
, test_run_it_ref = test_ref + '#speed-test'
, wu_ref = 'https://github.com/fitzgen/wu.js/'
, sp_yes = hh( 'span class="yes-no"', hh( 'img src="rsrc_web/img/pic_yes.png"' ) )
, sp_no = hh( 'span class="yes-no"', '' ) // hh( 'img src="rsrc_web/img/pic_no.png"' ) )
, comp_table_sep = [ { comp_table_sep : true } ]
, st_arr = [];
;
document.write([
hh.p([
hh( 'span class="right"', '' + hh( 'a href=".."', 'Home' ) )
, hh( 'span class="right"', '' + hh( 'a href="./test.html"', 'Test page' ) )
, hh( 'span class="right"', '' + hh( 'a href="' + github_ref + '"', 'GitHub' ) )
])
, hh( 'div class="clear"' )
, hh( 'div id="title"'
,[
,hh.h1( [ c_transfun ] )
, hh( 'p id="by" class=""', 'by G. Lathoud, January 2016' )
]
)
, hh( 'div class="clear"' )
, hh.p([
, c_transfun + ' is a JavaScript library that'
, ' lets you write ' + c_mfr + ' code that runs much faster than the equivalent '
, ' native ' + c_mfr + ' code:'
] )
, hh.p([
hh( 'img src="rsrc_web/img/jsperf_safari.png" class="mobile-spread-img"' )
])
, hh.p([
hh.strong( 'Update 2018-07-06:' )
, 'There is now a '
, hh( 'a href="https://www.npmjs.com/package/transfun"', 'Node.js package' )
, '.'
])
, highlight( 'Merging loops for speed' )
, hh.p([
, c_transfun + ' automatically merges consecutive loops'
, ' into one loop, '
, ' then generates fast code for that loop '
, ' (similar to stream fusion in → '
, hh( 'a href="' + haskell_ref + '"', 'Haskell' ) + ').'
])
, highlight( 'Extensibility' )
, hh.p([
, 'A domain-specific language is used to define ' + c_mfr + '. With this language, library users can '
, ' define other transformations: '
, hh.code( 'sum' ) + ', ' + hh.code( 'and' ) + ', ' + hh.code( 'or' ) + '...'
])
, highlight( 'For the hurried ones' )
, hh.p([
'...you can jump directly to the '
, hh( 'a href="#speed-result"', 'speed results' )
, '.'
])
, highlight( 'Plugins' )
, hh.dl([
dl_describe(
c_parallel + ' plugin'
, ['To split an ' + c_appfun + ' across web workers, using 1, some or all of the other available CPU cores: '
, hh( 'a href="' + parallel_example_ref + '"', 'Example of use' )
, ', '
, hh( 'a href="' + parallel_ref + '"', 'plugin source code' )
]
)
])
, highlight( 'Related topics' )
, hh.p([
'These might also interest you:'
])
, hh.ul([
hh.li([ '→ '
, hh( 'a href="http://chrisdone.com/posts/stream-composability"'
, 'Stream fusion and composability (Java 8 and Haskell) for newbies'
)
])
, hh.li([ '→ ', hh( 'a href="https://blogs.janestreet.com/flambda/"'
, 'A better inliner for OCaml, and why it matters'
)])
, hh.li([ '...and much more in '
, hh( 'a href="#annex-related-topics"', 'Annex' )
, '.'
])
])
, section_title_with_anchor( '', 'Contents' )
, hh( 'p id="contents"' )
, section_title_with_anchor( 'motivation', 'Motivation: Performance issue' )
, hh.p( 'Consider an array of objects provided by an unreliable data source:' )
, js_pre_code([
'arr = [ { p : 18, ... }, { p : null, ... }, { p : 47, ... }, ... ]',
' ^^^^',
' missing data (null or undefined)'
])
, hh.p([
'where we want to compute the sum of of the '
, hh.code( 'p' )
, ' values, ignoring the missing data.'
])
, hh.p([
'The native ' + c_mfr + ' array methods permit to write this '
, 'in a way that clearly separates the 3 steps (ES6 notation):'
])
, js_pre_code([
'arr.map((x) => x.p).filter((x) => x != null).reduce((a,b) => a + b)',
'',
'1. take the p values',
' 2. ignore missing data.',
' 3. sum...............'
])
, legend( 'Native code' )
, hh.p([
'The code structure is concise ' + hh.em( 'and' ) + ' close to that of a human language description. '
, 'This leads to very maintainable code - in particular '
, 'it can be changed with less chance to introduce a bug, as when we would write a for loop. '
])
, hh.p([
'BUT in performance-critical parts of a program, two issues arise: '
])
, hh.ul([
hh.li( '(1) one function call per array element,' )
, hh.li( '(2) several intermediary arrays created.' )
])
, js_pre_code([
'arr.map((x) => x.p).filter((x) => x != null).reduce((a,b) => a + b)',
' ^^ ^ ^^ ^ ^^',
' (1) (2) (1) (2) (1)',
])
, hh.p( 'To solve problem (1), one ends up writing ' + hh.code( 'for' ) + ' loops by hand:' )
, js_pre_code([
'// .map(".p")',
'var tmp_1 = new Array(n); // intermediary array (problem 2)',
'for (var i = 0; i < n; i++)',
' tmp_1[i] = arr[i].p;',
'',
'// .filter("!=null")',
'var tmp_2 = []; // intermediary array (problem 2)',
'for (var i = 0; i < n; i++) {',
' var v = tmp_1[i];',
' if (v != null)',
' tmp_2.push(v);',
'}',
'',
'// .reduce("+")',
'var sum = 0;',
'for (var n2 = tmp_2.length, i = 0; i < n2; i++)',
' sum = sum + tmp_2[i];',
])
, legend( '3-loop code (written by hand)' )
, hh.p( '...then, to solve problem (2), one merges the 3 loops into a single loop: ')
, js_pre_code([
'var sum = 0,',
'n = arr.length;',
'for (var i = 0; i < n; i++) {',
' var v = arr[i];',
' v = v.p; // .map(".p")',
' if (v != null) // .filter("!=null")',
' sum = sum + v; // .reduce("+")',
'}',
])
, legend( '1-loop code (written by hand)' )
, hh.p([
'This leads to a huge speedup (full results on → '
, hh( 'a href="' + jsperf_motivation + '"', 'jsPerf' )
, '):'
])
, hh.p([
hh( 'a href="' + jsperf_motivation + '"', hh( 'img src="rsrc_web/img/jsperf_motivation.png" title="click for full results on jsPerf" class="mobile-spread-img"' ))
])
, hh.p([
'...but the 1-loop code can be difficult to read, maintain and change without introducing bugs.'
])
, hh.p([
'Ideally, we would like to write code ' + hh.em( 'similar' ) + ' to this:'
])
, js_pre_code([
'arr.map((x) => x.p).filter((x) => x != null).reduce((a,b) => a + b)',
])
, '...and have it run as fast as the 1-loop code:'
, js_pre_code([
'var sum = 0,',
'n = arr.length;',
'for (var i = 0; i < n; i++) {',
' var v = arr[i];',
' v = v.p; // .map(".p")',
' if (v != null) // .filter("!=null")',
' sum = sum + v; // .reduce("+")',
'}',
])
, ' This is the goal of ' + c_transfun + '.'
, centered_pic( 'castlekids' )
, highlight( 'Interlude: Personal story' )
, hh.p([
'In frontend production code, I have been using for years '
, ' tools inspired from '
, hh( 'a href="http://bill.dojotoolkit.org/api/1.9/dojox/lang/functional"', hh.code( 'dojox.lang.functional' ))
, ', that solve problem 1, but not problem 2 (intermediary arrays). '
])
, hh.p([
'Concretely: After repeatedly writing things like this:'
])
, js_pre_code([
'var p_values = lib.map( lib.filter( arr, "!=null" ), ".p" );',
'// 4 2 1 3 5'
])
, hh.p([
'...I had two thoughts:'
])
, hh.ul([
hh.li( 'Can we improve the "read order" of the code (1,2,3,4,5)?' )
, hh.li( ' Can we get rid of the temporary array created between 3 and 4?' )
])
, centered_pic( 'alchemyequipment' )
, section_title_with_anchor( 'solution', 'The ' + c_transfun + ' solution' )
, hh.p(['Instead of '
, 'passing function arguments to ' + c_mfr + ' to produce a result value in 1 step: '
])
, js_pre_code([
'var result = arr.map((x) => x.p)',
' .filter((x) => x != null)',
' .reduce((a,b) => a + b);',
])
, legend( 'Native code' )
, hh.p([
'...' + c_transfun + ' has 2 steps, which rely on a similar but slightly different syntax, first passing ' + hh.em( 'code expressions' ) + ' to produce an ' + hh.em( 'application function' ) + ': '
])
, js_pre_code([
"var appfun = tfun.map( '.p' ).filter( '!=null' ).reduce( '+' );",
])
, legend( c_transfun + ' code' )
, hh.p([
'...then in a 2nd step, calling ' + c_appfun + ' on some data ' + c_arr + ' to produce a result:'
])
, js_pre_code([
"var result = appfun( arr ); // very fast!"
])
, hh.p([
'This runs very fast, because, behind the scenes, ' + c_transfun + ' generates single-loop code whenever possible:'
])
, js_pre_code( tfun.map( '.p' ).filter( '!=null' ).reduce( '+' ).getBodyCode() )
, legend(
'Internal code generated by ' + c_transfun
+ hh('br') + '(generated while this article loaded)'
)
, hh.p([
'If you want, you can jump directly to the '
, hh( 'a href="#speed-result"', 'speed results' )
, '.'
])
, centered_pic( 'function' )
, section_title_with_anchor( 'with-functions', 'Usage with function arguments' )
, hh.p([
c_transfun + ' also supports function arguments:'
])
, js_pre_code([
'var appfun = tfun.map((x)=>x.p).filter((x)=>x!=null)',
' .reduce((a,b)=>a+b);',
'var result = appfun( arr );'
])
, hh.p([
'...which generates an implementation with external function calls:'
])
, js_pre_code(
tfun.map(function (x) { return x.p })
.filter(function (x) { return x != null; })
.reduce( function (a, b ) { return a + b; })
.getBodyCode()
)
, legend(
'Internal code generated by ' + c_transfun
+ hh('br') + '(generated while this article loaded)'
)
, hh.p([
'The code runs slower than the one based on expression strings,'
, ' but still faster than the native array ' + c_mfr + ' methods.'
])
, highlight( 'Personal opinion' )
, hh.p([
'If I need conciseness and performance, I\'ll use expression strings. ',
'However, if I have a function that is either:'
])
, hh.ul([
hh.li( '(a) too complicate to reasonably be written as an expression string,' ),
hh.li( ' or (b) reused somewhere else,' )
])
, hh.p([ 'then I\'ll use a function argument. By the way, ',
'it is perfectly possible to mix the two:'
])
, js_pre_code([
"var appfun = tfun.map(someFunction).filter('!=null').reduce('+');"
])
, hh.p([
'Additionally, the flexibility provided by '
, hh( 'a href="#tval"', hh.code( 'tval' ) )
, ' and '
, hh( 'a href="#bind"', hh.code( 'bind' ) )
, ' permits to write code in the order that suits the context.'
])
, hh.p([
'If you like this type of topic, have a look at that article: <br> →'
, hh( 'a href="' + transducers_js_ref + '" target="_blank"'
, 'Understanding Transducers in JavaScript'
)
, '.'
])
, highlight( 'Acknowledgement' )
, hh.p([
'Many thanks to the reddit user '
, hh( 'a href="https://www.reddit.com/user/ugwe43to874nf4"', 'ugwe43to874nf4' )
, ' for the '
, hh( 'a href="https://www.reddit.com/r/javascript/comments/42wq9f/merging_loops_for_speed_in_javascript_library/"', 'feedback' )
, '.'
])
, centered_pic( 'toolbox' )
, section_title_with_anchor( 'toolbox', [
'Also predefined: ' + hh.code( 'mapIn' ) + ', ' + hh.code( 'and' ) + ', ' + hh.code( 'or' )
, ', ' + hh.code( 'o2keys')
, '...'
])
, hh.p([
'Beside ' + c_mfr + ', other transformations are also predefined:'
])
, hh.dl([
dl_describe(
c_mfr_etc
, 'take array input and loop left-to-right.'
)
, dl_describe(
c_mfr_etc_right
, 'take array input and loop ' + hh.em( 'right-to-left' ) + '.'
)
, dl_describe(
c_mfr_etc_in
, [ 'take ' + hh.em( 'object input' ) + ' and loop through keys: they are not array-specific. '
, 'Moreover, the key order is '
, hh( 'a href="' + nokeyorder_ref + '"'
, 'not guaranteed'
)
, '.'
]
)
, dl_describe(
c_o2arr_conv
, [
'convert objects to arrays and vice-versa (examples further below).'
]
)
, dl_describe(
c_arg
, [
'permits to define multiple arguments, instead of the standard single argument ' + c_current + '.'
]
)
, dl_describe(
c_range
, [
'permit to loop on numerical ranges.'
]
)
])
, highlight([
'Examples with ' + hh.code( 'and/or' ) + ':'
])
, js_pre_code([
"tfun.and // transformation function (arity 0)",
"tfun.and() // application function",
"",
"tfun.and() ([]) //>> true",
"tfun.and() ([ 1, 'a' ]) //>> 'a'",
"tfun.andRight()([ 1, 'a' ]) //>> 1",
"tfun.and() ([ 1, 'a', false, 33, null, 17 ]) //>> false",
"tfun.andRight()([ 1, 'a', false, 33, null, 17 ]) //>> null",
"",
"tfun.andIn()({ p:1, q:'aa', r:'xyz' }) //>> <one of: 1, 'aa' or 'xyz'>",
"tfun.andIn()({ p:1, q:null, r:'xyz' }) //>> null",
])
, js_pre_code([
"tfun.or() ([]) //>> false",
"tfun.or() ([ 1, 'a' ]) //>> 1",
"tfun.orRight()([ 1, 'a' ]) //>> 'a'",
"tfun.or() ([ false, 0, null ]) //>> null",
"tfun.orRight()([ false, 0, null ]) //>> false",
"",
"tfun.orIn()({ p:1, q:'aa', r:'' }) //>> <one of: 1 or 'aa'>",
"tfun.orIn()({ p:1, q:null, r:'' }) //>> 1",
"",
])
, highlight( 'Note about arity-0 transformations' )
, hh.p([
'Several transformation functions have arity 0 — i.e. need no parameter: '
])
, js_pre_code([
"tfun.and() // application function"
])
, hh.p([ 'which leads to the usage:' ])
, js_pre_code([
"tfun.and()([ 1, 'a' ]) // result: 'a'"
])
, hh.p([
, 'I chose '
, hh.em( 'not' )
, ' to permit shortcuts like '
, hh.code( 'tfun.and([ 1, \'a\' ])' )
, ' because it leads to inconsistencies as well as implementation issues, especially when '
, hh( 'a href="#chaining"', 'chaining' )
, '.'
, ' See also '
, hh( 'a href="https://github.com/glathoud/transfun/issues/4")', 'GitHub issue #4' )
, ' for more details.'
])
, highlight([
'"Values" extraction:'
])
, hh.dl([
dl_describe(
hh.code( 'o2values' )
, [
'converts an object to the array of its values:'
, js_pre_code([
"tfun.o2values()({ a:1, b:'xyz', c:null })",
"// *may* return:",
"[ 'xyz', 1, null ]"
])
, '"' + js_code( '*may*' ) + '": The array order is '
, hh( 'a href="' + nokeyorder_ref + '"'
, 'not guaranteed'
)
, '.'
]
)
])
, highlight([
'"Key" conversions:'
])
, hh.dl([
dl_describe(
hh.code( 'o2keys' )
, [
'converts an object to the array of its ' + hh.em( 'keys' ) + ' (it wraps ' + hh.code( 'Object.keys' ) + '): '
, js_pre_code([
"tfun.o2keys()({ a:1, b:'xyz', c:null })",
"// *may* return:",
"[ 'b', 'a', 'c' ]"
])
, '"' + js_code( '*may*' ) + '": The array order is '
, hh( 'a href="' + nokeyorder_ref + '"'
, 'not guaranteed'
)
, '.'
]
)
, dl_describe(
hh.code( 'keys2o' )
, [
'converts an array to an object. For example:'
, js_pre_code([
"tfun.keys2o()([ 'a', 'b', 'c' ])",
'// returns:',
"{ a:true, b:true, c:true }"
])
]
)
])
, highlight([
'"Key-value" conversions:'
])
, hh.dl([
dl_describe(
hh.code( 'o2kv' )
, [
'converts an object to the array of its key-value pairs:'
, js_pre_code([
"tfun.o2kv()({ a:1, b:'xyz', c:null })",
'// *may* return:',
"[ ['c', null], ['a', 1], ['b', 'xyz'] ]"
])
, '"' + js_code( '*may*' ) + '": The array order is '
, hh( 'a href="' + nokeyorder_ref + '"'
, 'not guaranteed'
)
, '.'
]
)
, dl_describe(
hh.code( 'kv2o' )
, [
'converts an array of key-value pairs to an object:'
, js_pre_code([
"tfun.kv2o()([ ['b', 'xyz'], ['a', 1], ['c', null] ])",
'// returns:',
"{ a:1, b:'xyz', c:null }"
])
]
)
])
, highlight( 'Multiple arguments:' )
, hh.dl([
dl_describe(
hh.code( 'arg' )
, [
'defines multiple arguments:'
, js_pre_code([
"tfun.arg( 'a,b,c' ).next( 'a+b*c' )"
, "// function (a,b,c) { return a+b*c; }"
])
]
)
])
, highlight( 'Ranges:' )
, hh.dl([
dl_describe(
c_range_direct
, [
'define numerical ranges:'
, js_pre_code([
"tfun.range()( 3, 7 ) // " + JSON.stringify( tfun.range()( 3, 7 ) )
, "tfun.range()( 7, 3, -1 ) // " + JSON.stringify( tfun.range()( 7, 3, -1 ) )
, ""
, "tfun.range()( 3, 7, 2 ) // " + JSON.stringify( tfun.range()( 3, 7, 2 ) )
, "tfun.range()( 7, 3, -2 ) // " + JSON.stringify( tfun.range()( 7, 3, -2 ) )
, ""
, "tfun.range()( 1.2, 9.1, 2.8 ) // " + JSON.stringify( tfun.range()( 1.2, 9.1, 2.8 ) )
])
]
)
, dl_describe(
c_range_of
, [
'define parameterized numerical ranges: '
, js_pre_code([
"tfun.rangeOf( 'begin', 'end' )"
, "tfun.rangeOf( 'begin', 'end', 'step' )"
])
, 'Example with constants:'
, js_pre_code([
"tfun.rangeOf( '3', '7' )() // [" + tfun.rangeOf( '3', '7' )() + "]"
])
, 'Example with variables:'
, js_pre_code([
"var appfun = tfun.arg( 'begin,end' ).rangeOf( 'begin', 'end' )"
, ""
, "// Generated code:"
, "" + tfun.arg( 'begin,end' ).rangeOf( 'begin', 'end' )
, ""
, '// Example use:'
, "appfun( 3, 7 ) // " + JSON.stringify( tfun.arg( 'begin,end' ).rangeOf( 'begin', 'end' )( 3, 7 ) )
])
])
, dl_describe(
'Ranges can be combined with other transformations.'
, [
hh.p( 'Example: pick a subset of a sparse array and modify it:' )
, js_pre_code([
"var appfun = tfun.arg( 'arr,begin,end' )"
, " .range( 'begin', 'end')"
, " .filter( 'v in arr')"
, " .map( 'arr[v]-k')"
, ""
, "// Generated code:"
, "" + tfun.arg( 'arr,begin,end' ).rangeOf( 'begin', 'end' ).filter( 'v in arr' ).map( 'arr[v]-k' )
])
]
)
])
, highlight( 'Published transformations and namespaces' )
, hh.p([
' The "published" transformations, i.e. transformations created with ' + js_code( 'tpub' ) + ', can be accessed by anyone through '
, js_code( 'tfun.*' ) + ' methods:'
])
, js_pre_code([
'tfun.map',
'tfun.filter',
'// etc.'
])
, hh.p([ 'For example:' ])
, js_pre_code([
"var appfun = tfun.map( '.p' ).filter( '!=null' ).reduce( '+' );",
])
, centered_pic( 'oldcpu' )
, section_title_with_anchor( 'practical', 'Negligible CPU overhead' )
, hh.p([
'As mentionned above, '
, 'the '
, c_transfun
, ' approach has two steps:'
])
, js_pre_code([
"var appfun = tfun.map( '.p' ).filter( '!=null' ).reduce( '+' );",
"var result = appfun( arr ); // very fast!"
])
, hh.p([
'The cost of the first step — creating the '
, js_code( 'appfun' )
, ' — is negligible (see →'
, hh( 'a href="https://github.com/glathoud/transfun/issues/2" class="issue_closed"'
, '#2' )
, '), so one can write the two steps in a single line:'
])
, js_pre_code([
"var result = tfun.map( '.p' ).filter( '!=null' ).reduce( '+' )( arr );",
])
, hh.p([
'However, I personally don\'t like the order in which the terms of that line read,'
, ' but that can be fixed. See the next Section.'
])
, centered_pic( 'pipechair' )
, section_title_with_anchor( 'tval', 'Convenient pipe-like order using ' + c_tval )
, hh.p([
'If you write things in a single line:'
])
, js_pre_code([
"var result = tfun.map( '.p' ).filter( '!=null' ).reduce( '+' )( arr )",
"// 2 3 4 1"
])
, hh.p([
'...the reading order might be a bit confusing, because the input value '
, hh.code( 'arr' )
, ' is at the end (1), while the rest (2,3,4) follows a pipe-like order.'
])
, hh.p([
'In such cases you can use ' + c_tval + ' to improve the reading order, putting the data '
, c_arr
, ' first:'
])
, js_pre_code([
"var result = tval( arr )( tfun.map('.p').filter('!=null').reduce('+') );",
"// 1 2 3 4"
])
, hh.p([
"There is no magic here: "
, c_tval
, ' simply applies the appfun (2,3,4) on its data parameter (1). '
])
, hh.p([ ' Generally:' ])
, js_pre_code([
'tval( <data> )( <appfun> ) === <appfun>( <data> )'
])
, centered_pic( 'now_later' )
, section_title_with_anchor( 'bind', 'Hiding away complexity using ' + c_bind )
, hh.p([
'It is not realistic to write code strings that are too complex/too long. '
])
, hh.p([
, 'One solution hides away complex processing of a piece of data using '
, hh( 'a href="#with-functions"', 'function arguments' )
, '. '
])
, hh.p([
'Another solution sticks to '
, hh.em( 'short' )
, ' code strings, and uses ', hh.code( 'this' ) , ' and ', hh.code( 'bind' )
, ' to hide away complexity into an '
, ' object, as shown below.'
])
, hh.p([
hh('small', [
' Note: functions and RegExps are also objects in JavaScript. '
])
])
, highlight( 'Example: ' + js_code( 'bind' ) + ' a function' )
, js_pre_code([
"// Split text lines and parse each line into an object"
, "data = tval("
, " csv.split( /[\\r\\n]+/ )"
, ")("
, " tfun.filter( '' )"
, " .map( 'this(v.split(\",\"))' )"
, " .bind( extract_one )"
, ");"
, ""
, "function extract_one( array_of_strings ) {"
, " // Returns an object"
, " // (too many steps to be reasonably coded in a code string)"
, "}"
])
, highlight( 'Example: ' + js_code( 'bind' ) + ' a RegExp' )
, hh.p([
'Here is a ' + js_code( 'bind' ) + ' example with a RegExp outside of the code string (goodbye double backslashes): '
])
, js_pre_code([
'// Parse the 3rd string into an object',
'transaction_a = tval(',
' arr[ 3 ].split( /\s+/ )',
')(',
" tfun.filter( '' )",
" .map( '(v=v.match(this)),' +",
" '{name:v[1], delta:parseFloat(v[2])}' )",
" .bind( /^([^\\+\\-]+)([\\+\\-]\\S+)$/ )",
");"
])
, highlight( 'Example: ' + js_code( 'bind' ) + ' an object' )
, hh.p([
'Here is a ' + js_code( 'bind' ) + ' example with an object containing a parameter ' + js_code( 'v_in' ) + ':'
])
, js_pre_code([
"// Convert an object to ready-to-print text"
,"v_out = tval("
," final_share"
,")("
," // Data extraction, sorted per key (name)"
," tfun.o2kv()"
," .sorted( 'a[0]<b[0] ? -1 : +1' )"
," // Presentation"
," .map( 'v[0] + \": \" + this.v_in * v[1]' ) // <<< here: this.v_in"
," .bind( { v_in : v_in } ) // Parameter: v_in"
,")"
," .join( '\\n' )"
,";"
])
, hh.p([
'Note: instead of: '
, js_pre_code( " .map( 'v[0] + \": \" + this.v_in * v[1]' ) // <<< here: this.v_in" )
, '...we could put the '
, js_code( 'v_in' )
, ' value directly into the code string:'
, js_pre_code( " .map( 'v[0] + \": \" + ' + v_in + ' * v[1]' )" )