forked from xpl/gop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseless.micro.js
5623 lines (4121 loc) · 219 KB
/
useless.micro.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
------------------------------------------------------------------------
Entry point.
------------------------------------------------------------------------
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* As we do not run macro processor on server scripts, $include reduces to
built-in require (if running in Node.js environment)
======================================================================== */
if (typeof require !== 'undefined') {
_ = require ('underscore')
$include = require }
/* Bootstrap code (couple of absolutely urgent fixes to underscore.js)
======================================================================== */
_ = (function () {
_.mixin ({
zipWith: function (rows, zippo) {
return _.reduce (_.rest (rows), function (memo, row) {
return _.times (Math.max ((memo && memo.length) || 0, (row && row.length) || 0), function (i) {
return zippo (memo && memo[i], row && row[i]) }) }, _.first (rows)) } })
if ('a1 b2 c3' !== _.zipWith ([['a','b','c'], [1,2,3]], function (a, b) { return a + b }).join (' ')) {
throw new Error ('_.zipWith broken') }
return _ }) ()
/* Tests stub
*/
_.tests = {}
_.deferTest = _.withTest = function (name, test, subj) { subj () }
/* Internal dependencies
======================================================================== */
/* Platform abstraction layer
*/
_.platform = function () {
if ((typeof window !== 'undefined') && (window._.platform === arguments.callee)) {
if (navigator.platform && navigator.platform.indexOf) {
return _.extend ({ engine: 'browser'},
((navigator.platform .indexOf ("Linux arm") >= 0)
|| (navigator.platform .indexOf ("Android") >= 0)
|| (navigator.userAgent.indexOf ("Android") >= 0) ? { touch: true, system: 'Android' } :
((navigator.platform .indexOf ("iPad") >= 0) ? { touch: true, system: 'iOS', device: 'iPad' } :
((navigator.platform .indexOf ("iPhone") >= 0)
|| (navigator.platform .indexOf ("iPod") >= 0) ? { touch: true, system: 'iOS', device: 'iPhone' } : {} )))) } }
if ((typeof global !== 'undefined') && (global._.platform === arguments.callee)) {
return { engine: 'node' } }
return {} }
_.global = function () {
return ((_.platform ().engine === 'browser') ? window :
(_.platform ().engine === 'node') ? global : undefined) }
_.defineGlobalProperty = function (name, value, cfg) {
if (_.global ()[name] !== undefined) {
throw new Error ('cannot defineGlobalProperty: ' + name + ' is already there') }
Object.defineProperty (_.global (), name, _.extend ({
enumerable: true,
get: (_.isFunction (value) && value.length === 0) ? value : _.constant (value) }, cfg))
return value }
/* Use this helper to override underscore's functions
======================================================================== */
$overrideUnderscore = function (name, genImpl) {
return _[name] = genImpl (_[name]) }
/* alert2 for ghetto debugging in browser
======================================================================== */
if (_.platform ().engine !== 'browser') {
_.defineGlobalProperty ('alert', function (args) {
var print = ((_.global ()['log'] &&
_.partial (log.warn, log.config ({ stackOffset: 2 }))) ||
console.log)
print.apply (print, ['ALERT:'].concat (_.asArray (arguments))) }) }
_.defineGlobalProperty ('alert2', function (args) {
alert (_.map (arguments, _.stringify).join (', ')); return arguments[0] })
;
/* converts 'arguments' (and any other array mimick) to real Array
======================================================================== */
_.withTest (['stdlib', 'asArray'], function () {
(function (a, b) {
var args = _.asArray (arguments)
$assert (_.isArray (args))
$assert (args.length === 2)
$assert (args[0] === a)
$assert (args[1] === b) }) (42, 43) }, function () { _.extend (_, {
asArray: function (arrayMimick) {
return [].splice.call (arrayMimick, 0) } }) })
/* Argument count tracking module (provides hinting to several metaprogramming
utilities, like property definitions)
======================================================================== */
/* NOTE: "rest argument" is a term from upcoming ECMAScript 6 standard,
denoting the "..." thing in "f(a,b,...)"-type signatures.
Although it's best known elsewhere as 'variable argument list',
and the "rest argument" term is really confusing to most of
people, we should take course on the future language prospects
that will soon become widely recognized reality for everyone.
*/
_.withTest ('argcount tracking', function () {
var none = function () {}
var one = function (a) {}
var three = function (a, b, c) {}
var many = $restArg (function () {})
$assert (_.noArgs (none) === true)
$assert (_.hasArgs (none) === false)
$assert (_.numArgs (three) === 3)
$assert (_.hasArgs (three) === true)
$assert (_.restArg (many) === true)
$assert (_.noArgs (many) === false)
$assert (_.oneArg (one) === true)
var sameAsThree = _.withSameArgs (three, function () {})
var oneArgLess = _.withArgs (_.numArgs (three) - 1, _.restArg (three), function () {})
$assert ([_.numArgs (sameAsThree), _.restArg (sameAsThree)], [3, false])
$assert ([_.numArgs (oneArgLess ), _.restArg (oneArgLess )], [2, false])
}, function () { _.extend (_, {
/* Querying
*/
numArgs: function (fn) {
return fn._ac === undefined ? fn.length : fn._ac }, // short name for speed
restArg: function (fn) {
return fn._ra || false }, // short name for speed
noArgs: function (fn) {
return (_.numArgs (fn) === 0) && !fn._ra },
hasArgs: function (fn) {
return (_.numArgs (fn) > 0) && !fn._ra },
oneArg: function (fn) {
return (_.numArgs (fn) === 1) && !fn._ra },
/* Setting
*/
withRestArg: _.defineGlobalProperty ('$restArg',
function (fn) {
Object.defineProperty (fn, '_ra', { enumerable: false, writable: true, value: true })
return fn }),
withArgs: function (numArgs, restArg, fn) {
if (numArgs !== undefined) {
Object.defineProperty (fn, '_ac', { enumerable: false, writable: true, value: numArgs }) }
if (restArg !== undefined) {
Object.defineProperty (fn, '_ra', { enumerable: false, writable: true, value: restArg }) }
return fn },
withSameArgs: function (other, fn) {
return _.withArgs (_.numArgs (other), _.restArg (other), fn) } }) })
/* Adds argcount tracking to some underscore functions.
Will test it for speed in future, and if slow in app code,
will be de-mounted, thus sacrificing clarity in some places.
======================================================================== */
$overrideUnderscore ('memoize',
function (memoize) {
return function (fn) {
return _.withSameArgs (fn, memoize (fn)) } })
$overrideUnderscore ('partial',
function (partial) {
return $restArg (function (fn) {
return _.withArgs (
Math.max (0, _.numArgs (fn) - (arguments.length - 1)), fn._ra,
partial.apply (this, arguments)) }) })
$overrideUnderscore ('bind',
function (bind) {
return $restArg (function (fn, this_) {
return _.withArgs (
Math.max (0, _.numArgs (fn) - (arguments.length - 2)), fn._ra,
bind.apply (this, arguments)) }) })
;
/* Limits function to given number of arguments
======================================================================== */
_.arity = function (N, fn) { return function () {
return fn.apply (this, _.first (arguments, N)) }}
_.arity0 = function (fn) { return function () {
return fn.call (this) }}
_.arity1 = function (fn) { return function (a) {
return fn.call (this, a) }}
_.arity2 = function (fn) { return function (a, b) {
return fn.call (this, a, b) }}
_.arity3 = function (fn) { return function (a, b, c) {
return fn.call (this, a, b, c) }}
_.arityFn = function (N) { return _['arity' + N] }
/* A version of _.partial that binds to tail of argument list
======================================================================== */
_.tails = $restArg (function (fn) { var tailArgs = _.rest (arguments)
return function () {
return fn.apply (this, _.asArray (arguments).concat (tailArgs)) }})
_.tails2 = $restArg (function (fn) { var tailArgs = _.rest (arguments)
return function (a) {
return fn.apply (this, [a].concat (tailArgs)) }})
_.tails3 = $restArg (function (fn) { var tailArgs = _.rest (arguments)
return function (a, b) {
return fn.apply (this, [a, b].concat (tailArgs)) }})
/* Flips function signature (argument order)
======================================================================== */
_.flip = function (fn) {
if (_.restArg (fn)) { return $restArg (function () {
return fn.apply (this, _.asArray (arguments).reverse ()) }) }
else {
switch (_.numArgs (fn)) {
case 0:
case 1: return fn
case 2: return _.flip2 (fn)
case 3: return _.flip3 (fn)
default: throw new Error ('flip: unsupported arity') } } }
_.flip2 = function (fn) { return function (a, b) {
return fn.call (this, b, a) }}
_.flip3 = function (fn) { return function (a, b, c) {
return fn.call (this, c, b, a) }}
/* Logical composition operators
======================================================================== */
_.or = function (a, b) { return function () {
return a.apply (this, arguments) || b.apply (this, arguments) }},
_.and = function (a, b) { return function () {
return a.apply (this, arguments) && b.apply (this, arguments) }},
_.not = function (x) { return function () {
return !x.apply (this, arguments) } }
/* Y combinator (for anonymous recursive functions)
======================================================================== */
_.withTest (['function', 'Y combinator'], function () {
var countTo5 = _.Y (function (self) {
return function (n) {
return n >= 5 ? n : self (n + 1) } })
$assert (countTo5 (0), 5) }, function () { _.extend (_, {
Y: function (eatSelf) {
var self = eatSelf (function () {
return self.apply (this, arguments) }); return self } }) });
/* converts regular things like map/zip to hyper versions, that traverse
deep structures (tested later, via its derivatives: zipZip/mapMap etc)
======================================================================== */
/* Operator argument is the thing that walks down the tree and transforms it.
But its predicate gets called only on the leaves of a tree (end values).
Essentially, it abstracts you from structure, making it 'transparent'
for any kind of previously defined one-dimensional operators like
map/filter/zip/reduce/etc.
Example: hyperMap = _.hyperOperator (_.unary, _.map2)
hyperZip = _.hyperOperator (_.binary, _.zip2)
*/
(function () {
/* N number denotes how many arguments underlying operation accepts
*/
_.hyperOperator = function (N, operator, diCaprioPredicate, nonTrivial) {
var arity = _.arityFn (N) || _.identity
var weNeedToGoDeeper = (diCaprioPredicate || _.goDeeperWhenFirstArgumentIsGood) (N, nonTrivial || _.isNonTrivial)
return function () { var subOperator = _.last (arguments)
return _.Y (function (hyperOperator_) { var hyperOperator = _.tails (operator, arity (hyperOperator_))
return function () {
return (weNeedToGoDeeper (arguments) ?
hyperOperator :
subOperator)
.apply (this, arguments) } }).apply (this, _.initial (arguments)) } }
/* Combinatoric complexity classifiers for exact configuration of hyperOperator behavior
*/
_.goDeeperWhenFirstArgumentIsGood= function (N, canGoDeeper) {
return function (args) { return (args.length > 0) ? canGoDeeper (args[0]) : false } }
_.goDeeperAlwaysIfPossible= function (N, canGoDeeper) {
if (N === 0) { return _.constant (false) }
else if (N === 1) { return function (args) { return canGoDeeper (args[0]) } }
else if (N === 2) { return function (args) { return canGoDeeper (args[0]) || canGoDeeper (args[1]) } }
else { return function (args) { return _.some (_.asArray (args), canGoDeeper) } } }
_.goDeeperOnlyWhenNessesary = function (N, canGoDeeper) {
if (N === 0) { return _.constant (false) }
else if (N === 1) { return function (args) { return canGoDeeper (args[0]) } }
else if (N === 2) { return function (args) { return canGoDeeper (args[0]) && canGoDeeper (args[1]) } }
else { return function (args) { return _.every (_.asArray (args), canGoDeeper) } } }
_.isTrivial = function (x) { return _ .isEmpty (x) || _.isString (x) || _.isNumber (x) ||
!(_.isStrictlyObject (x) || _.isArray (x)) || _.isPrototypeInstance (x) || _.isMeta (x) }
_.isMeta = _.constant (false)
_.isNonTrivial = _.not (_.isTrivial)
/* Self-descriptive constants (for clarity)
*/
_.binary = 2
_.unary = 1 }) ()
/* Generates higher order stuff from regular routine
======================================================================== */
_.withTest (['function', 'higherOrder'], function () {
var file = []
var write = function (x) { file.push (x) }
var writes = _.higherOrder (write)
_.times (3, writes ('foo'))
$assert (file, ['foo', 'foo', 'foo']) }, function () {
_.higherOrder = function (fn) { return _.partial (_.partial, fn) } })
/* coerces x|fn()→x to x (useful for configuration parameters)
======================================================================== */
_.deferTest (['function', 'eval/evals'], function () {
var cfg = {
value1: 42,
value2: function () { return 42 },
value3: _.property ('number')
}
var eval = _.evals ({ number: 42 }) // higher order
$assert (_.eval (cfg.value1), _.eval (cfg.value2), eval (cfg.value3), 42) }, function () {
_.eval = function (x) {
return _.isFunction (x) ? x.call (this) : x }
_.evals = function (__args__) {
var arguments_ = arguments
return function (x) {
return _.isFunction (x) ? x.apply (this, arguments_) : x } } })
/* in rhyme with _.property, this one calls a method
======================================================================== */
_.method = function (name) {
var args = _.rest (arguments)
return function (obj) {
return obj[name].apply (obj, args) } }
/* Converts between calling conventions
======================================================================== */
_.asFreeFunction = function (fn) { return function (this_, restArg) {
return fn.apply (this_, _.rest (arguments)) } }
_.asMethod = function (fn) { return function () {
return fn.apply (undefined, [this].concat (_.asArray (arguments))) } }
/* Wrapper generator
======================================================================== */
_.wrapper = function (fn, wrapper) {
return _.withSameArgs (fn, function () {
var this_ = this
var arguments_ = arguments
return wrapper (function (additionalArguments) {
fn.apply (
this_,
_.asArray (arguments_).concat (additionalArguments)) }) }) }
/* _.once
======================================================================== */
_.withTest (['function', 'once'], function () {
$assertCalls (1, function (mkay) {
var f = _.once (function () { mkay () })
f ()
f () }) }, function () {
_.once = function (fn) {
var called = false
return function () {
if (!called) { called = true
return fn.apply (this, arguments) } } } })
/* _.withTimeout
======================================================================== */
_.deferTest (['function', 'withTimeout'], function (testDone) {
_.withTimeout ({
maxTime: 10,
expired: function () { $fail } },
function (done) { done () })
_.withTimeout ({
maxTime: 10,
expired: function (then) { testDone () } },
function (done) { _.delay (done, 20) },
function () { // 'then' should not be called if expired (though you may call it explicitly at expired() callback)
$fail })
}, function () {
_.withTimeout = function (cfg, what, then) {
var expired = false
var timeout = setTimeout (function () {
expired = true
if (cfg.expired) {
cfg.expired (then) } }, cfg.maxTime)
what (function () {
if (!expired) {
clearTimeout (timeout)
if (then) {
then.apply (this, arguments) } } }) } })
/* Sequential composition operator (inverted _.compose, basically)
======================================================================== */
_.withTest (['function', 'sequence / then'], function () {
var context = { foo: 'bar' }
var makeCookies = function (from) { $assert (this === context)
return 'cookies from ' + from }
var eatCookies = function (cookies) { $assert (this === context)
return 'nice ' + cookies }
var lifeProcess = makeCookies.then ? // available in both notations
makeCookies.then (eatCookies) :
_.then (makeCookies, eatCookies)
var anotherWay = _.sequence (makeCookies, eatCookies)
var wayAnother = _.sequence ([makeCookies, eatCookies])
$assert (lifeProcess.call (context, 'shit'), 'nice cookies from shit')
$assert (anotherWay.call (context, 'shit'), 'nice cookies from shit')
$assert (wayAnother.call (context, 'shit'), 'nice cookies from shit')
$assert (_.sequence ([]).call (context, 'foo'), 'foo') }, function () {
_.sequence = function (arg) { // was _.flip (_.compose) before... but it needs performance
var chain = _.isArray (arg) ? arg : _.asArray (arguments)
var length = chain.length
return (length === 0) ? _.identity : function (x) {
for (var i = 0; i < length; i++) { x = chain[i].call (this, x) }
return x } }
_.seq = _.sequence
_.then = function (fn1, fn2) { return function (args) {
return fn2.call (this, fn1.apply (this, arguments)) }} })
;
/* Basic utility for writing data-crunching functional expressions.
======================================================================== */
_.makes = function (constructor) {
return function () {
switch (arguments.length) { /* cant use .apply or .call with 'new' syntax */
case 0:
return new constructor ()
case 1:
return new constructor (arguments[0])
case 2:
return new constructor (arguments[0], arguments[1])
default:
throw new Error ('not supported') } } }
_.asString = function (what) { return what + '' }
_.typeOf = function (what) {
return typeof what }
_.count = function (what) { // cannot override _.length
return what.length }
_.array = _.tuple = function () {
return _.asArray (arguments) }
_.concat = function (a, b) {
if (_.isArray (a)) {
return a.concat ([b]) }
else {
return a + b } }
_.atIndex = function (n) {
return function (arr) { return arr[n] } }
_.applies = function (fn, this_, args) {
return function () { return fn.apply (this_, args) } }
_.prepends = function (what) {
return function (to) {
return what + to } }
_.appends = function (what) {
return function (to) {
return to + what } }
_.join = function (arr, s) { return arr.join (s) }
_.joinWith = _.flip2 (_.join)
_.joinsWith = _.higherOrder (_.joinWith)
_.sum = function (a, b) {
return (a || 0) + (b || 0) }
_.subtract = function (a, b) {
return (a || 0) - (b || 0) }
_.mul = function (a, b) {
return (a || 0) * (b || 0) }
_.equal = function (a, b) {
return a === b }
_.sums = _.plus = _.higherOrder (_.sum)
_.subtracts = _.minus = _.higherOrder (_.subtract)
_.muls = _.higherOrder (_.mul)
_.equals = _.higherOrder (_.equal)
_.largest = function (a, b) { // FFFFUUUU: underscore already taken _.max for its dirty needs.
if (isNaN (a) && isNaN (b)) {
return NaN }
else if (isNaN (a)) {
return b }
else if (isNaN (b)) {
return a }
else {
return Math.max (a, b) } }
_.notZero = function (x) { return x !== 0 }
_.propertyOf = function (obj) { return function (prop) { // inverted version of _.property
return obj[prop] }}
;
/* isTypeOf (bootstrap for OOP.js)
======================================================================== */
_.isInstanceofSyntaxAvailable = function () { var e = new Error ()
try { return e instanceof Error }
catch (e) { return false } }
_.isTypeOf_ES4 = function (constructor, what) {
while (what) {
if (what.constructor === constructor) {
return true }
what = what.constructor.$base }
return false }
_.isTypeOf_ES5 = function (constructor, what) {
return what instanceof constructor }
_.isTypeOf = _.isInstanceofSyntaxAvailable () ? _.isTypeOf_ES5 : _.isTypeOf_ES4
_.isPrototypeInstance = function (x) {
return x && x.constructor && _.isPrototypeConstructor (x.constructor) }
_.isPrototypeConstructor = function (x) {
return (x && (x.$definition !== undefined)) || false }
/* Useful for defining functions that accept either [x] or x as argument
======================================================================== */
_.coerceToArray = function (x) {
return (x === undefined) ? [] : (_.isArray (x) ? x : [x]) }
/* Fixes _.isArray to account objects that derive from Array prototype
======================================================================== */
_.deferTest (['type', 'isArray'], function () {
var CustomArray = $extends (Array, {
method: function () { return 42 } })
$assert (_.isArray (new CustomArray ())) }, function () {
$overrideUnderscore ('isArray', function (isArray) {
return function (x) {
return _.isTypeOf (Array, x) || isArray (x) } }) })
/* Better _.matches / $assertMatches: +regexp feature, +deep matching
======================================================================== */
_.deferTest (['type', 'matches(regex)'], function () {
var test = function (a, pattern) {
$assert (_.match (a, pattern))
$assert (_.matches (pattern) (a))
$assertMatches (a, pattern) }
$assertFails (function () {
test ({ foo: [1,2], bar: 2 },
{ foo: [3], bar: 2 })
test ({ bar: { foo: 'foo' } },
{ bar: { foo: /[0-9]+/ } })
test ({}, { foo: 1 }) })
$assertFails (function () {
test ({ foo: 1 }, undefined) // differs from original impl in that
test ('.DS_Store', /.+\.js/) }) // regression
test ({ foo: [1,2], bar: 2 },
{ foo: [2] })
test ({ bar: { foo: '123', qux: 1 } },
{ bar: { foo: /[0-9]+/ } })
test ({ foo: 1 }, {}) },
function () { _.mixin ({
matches: function (pattern) {
return ((arguments.length === 0) && _.constant (true)) ||
_.tails2 (_.match, pattern) },
match: function (a, ptrn) {
return (a === ptrn)
|| (_.isArray (a) && _.isArray (ptrn) && _.arrayMatch (a, ptrn))
|| (_.isObject (a) && _.isObject (ptrn) && _.objectMatch (a, ptrn))
|| (_.isTypeOf (RegExp, ptrn) && _.isString (a) && (a.match (ptrn) !== null)) },
arrayMatch: function (a, pattern) {
return _.every (pattern, _.propertyOf (_.index (a))) },
objectMatch: function (a, pattern) {
return _.reduce (_.pairs (pattern),
function (result, kv) {
return result && _.match (a[kv[0]], kv[1]) }, true) } }) })
/* POD data types
======================================================================== */
_.withTest (['type', 'POD'], function () {
$assert (_.every ([[], {}, 42, 'foo', null, undefined, true].map (_.isPOD)))
$assert (_.every ([/foo/, new Date ()].map (_.isNonPOD)))
}, function () { _.extend (_, {
isNonPOD: function (v) {
return (v && v.constructor) &&
(v.constructor !== Object) &&
(v.constructor !== Array) &&
(v.constructor !== String) &&
(v.constructor !== Number) &&
(v.constructor !== Boolean) },
isPOD: function (v) {
return !_.isNonPOD (v) } }) })
/* Numbers
======================================================================== */
_.withTest (['type', 'numbers'], function () {
$assert (_.every (_.map ([0, 1, -7, 200003, 12344567788], _.arity1 (_.not (_.isDecimal)))))
$assert (_.every (_.map ([0.1, -0.001, 0.0001, -0.000001, 0.000001], _.arity1 ( _.isDecimal))))
$assert (_.isDecimal (0.003, 0.01), false) // custom tolerance
}, function () {
if (typeof Number.EPSILON === 'undefined') {
Object.defineProperty (Number, 'EPSILON', { enumerable: true,
get: _.constant (2.2204460492503130808472633361816E-16) }) } // NodeJS lack this
_.extend (_, {
isDecimal: function (x, tolerance) {
if (!_.isNumber (x) || _.isNaN (x)) {
return false }
else {
return (Math.abs (Math.floor (x) - x) > (tolerance || Number.EPSILON)) } } }) })
/* 'empty' classifiers (fixes underscore shit)
======================================================================== */
_.withTest (['type', 'empty-centric routines'], function () {
$assert (_.coerceToEmpty (42), undefined)
$assert (_.coerceToEmpty ([42]), [])
$assert (_.coerceToEmpty ({ foo: 42 }), {})
$assert ([
_.isNonemptyString ('foo'),
_.isNonemptyString (''),
_.isNonemptyString ([])], [true, false, false])
$assert (_.isEmptyArray ([]), true)
$assert (_.isEmptyArray ([1,2,3]), false)
$assert (_.isEmptyArray (undefined), false)
$assert (_.isEmptyArray (null), false)
$assert (_.isEmptyArray (''), false)
$assert (_.isEmptyObject ({}), true)
$assert (_.isEmptyObject ([]), false)
$assert (_.isEmptyObject ({ foo: 1 }), false)
$assert (_.isEmptyObject (undefined), false)
$assert (_.isEmptyObject (null), false)
$assert (_.isEmptyObject (''), false)
$assert (_.isEmptyObject (0), false)
$assert (_.isEmptyObject (false), false)
$assert (_.isEmpty (0), false)
$assert (_.isEmpty (false), false)
$assert (_.isEmpty (/.+\.js/), false) // regression
$assert (_.isEmpty (null), true)
$assert (_.isEmpty ({}), true)
$assert (_.isEmpty ([]), true)
$assert (_.isNonempty ('foo'), true) // negated _.isEmpty
$assert (_.coerceToUndefined (undefined), undefined)
$assert (_.coerceToUndefined ({}), undefined)
$assert (_.coerceToUndefined ([]), undefined)
$assert (_.coerceToUndefined (''), undefined)
$assert (_.coerceToUndefined (null), undefined)
$assert (_.coerceToUndefined (0), 0)
$assert (_.coerceToUndefined (Math.NaN), undefined)
$assert (_.coerceToUndefined (false), false)
$assert (_.coerceToUndefined ({ foo: 1 }), { foo: 1 })
$assert (_.coerceToUndefined ([1, 2]), [1, 2]) }, function () { _.extend (_, {
/* These two override underscore's one, because the original stuff is semantically incorrect.
A word needs to be spoken here, because it's not the first routine we override, and not
the last. So what about semantics?
For instance, 0 and false should NOT be treated as empty. But they are (in underscore).
This is ridiculous. Can think of hundreds of applications of the correct impl., and
just none of that for the creeped original version. Why would one ever need to treat 0
as 'empty'? Shit, its just a regular number, no worse or better than 1 or 42. And 'false'?
Keep hands off boolean logic. If someone states that something's false - it's false, not
a 'void non-existing piece of nothing'. It's a value. It has value. And it's false. Oh,
fock, just don't get me started...
*/
isEmpty: function (obj) {
return _.coerceToUndefined (obj) === undefined },
isNonempty: function (obj) {
return _.coerceToUndefined (obj) !== undefined },
isEmptyObject: function (v) {
return !_.isArray (v) &&
!_.isFunction (v) &&
_.isObject (v) &&
(_.keys (v).length === 0) },
isStrictlyObject: function (v) {
return (v && (typeof v === 'object')) ? true : false },
isEmptyArray: function (v) {
return _.isArray (v) && v.length === 0 },
isNonemptyString: function (v) {
return (typeof v === 'string') && (v.length > 0) },
coerceToEmpty: function (x) {
if (_.isArray (x)) { return [] }
else if (_.isStrictlyObject (x)) { return {} }
else { return undefined } },
/* Projects a variety of input values through 'undefined/non-undefined' dichotomy.
*/
coerceToUndefined: function (v) {
return ((v === undefined) ||
(v === null) ||
(v === Math.NaN) ||
(v === '') ||
(_.isPOD (v) &&
(_.isEmptyObject (v) ||
(v.length === 0)))) ? undefined : v } })} )
;
/* Tired of wrapping JSON.parse to try/catch? Here's solution.
Also, it's two-way (can either parse, or stringify).
======================================================================== */
_.json = function (arg) {
if (typeof arg === 'string') {
try { return JSON.parse (arg) }
catch (e) { return {} } }
else {
return JSON.stringify (arg) } }
/* Object stringifier
======================================================================== */
_.deferTest (['type', 'stringify'], function () {
var complex = { foo: 1, nil: null, nope: undefined, fn: _.identity, bar: [{ baz: "garply", qux: [1, 2, 3] }] }
complex.bar[0].bar = complex.bar
var renders = '{ foo: 1, nil: null, nope: undefined, fn: <function>, bar: [{ baz: "garply", qux: [1, 2, 3], bar: <cyclic> }] }'
var Proto = $prototype ({})
$assert (_.stringify (Proto), '<prototype>')
$assert (_.stringify (123), '123')
$assert (_.stringify (complex), renders)
var obj = {}
$assert (_.stringify ([obj, obj, obj]), '[{ }, <ref:1>, <ref:1>]') }, function () {
_.stringify = function (x, cfg) { return _.stringifyImpl (x, [], [], 0, cfg || {}, -1) }
_.stringifyImpl = function (x, parents, siblings, depth, cfg, prevIndent) {
if (x === $global) {
return '$global' }
var customFormat = cfg.formatter && cfg.formatter (x)
if (customFormat) {
return customFormat }
else if (parents.indexOf (x) >= 0) {
return cfg.pure ? undefined : '<cyclic>' }
else if (siblings.indexOf (x) >= 0) {
return cfg.pure ? undefined : '<ref:' + siblings.indexOf (x) + '>' }
else if (x === undefined) {
return 'undefined' }
else if (x === null) {
return 'null' }
else if (_.isFunction (x)) {
return cfg.pure ? x.toString () : (_.isPrototypeConstructor (x) ? '<prototype>' : '<function>') }
else if (typeof x === 'string') {
return _.quoteWith ('"', x) }
else if (_.isObject (x) && !((typeof $atom !== 'undefined') && ($atom.is (x)))) { var isArray = _.isArray (x)
var pretty = cfg.pretty || false
if ((_.platform ().engine === 'browser')) {
if (_.isTypeOf (Element, x)) {
return '<' + x.tagName.lowercase + '>' }
else if (_.isTypeOf (Text, x)) {
return '@' + x.wholeText } }
if (x.toJSON) {
return _.quoteWith ('"', x.toJSON ()) } // for MongoDB ObjectID
if (!cfg.pure && (depth > (cfg.maxDepth || 5) || (isArray && x.length > (cfg.maxArrayLength || 30)))) {
return isArray ? '<array[' + x.length + ']>' : '<object>' }
var parentsPlusX = parents.concat ([x])
siblings.push (x)
var values = _.pairs (x)
var oneLine = !pretty || (values.length < 2)
var indent = prevIndent + 1
var tabs = !oneLine ? '\t'.repeats (indent) : ''
if (pretty && !isArray) {
var max = _.reduce (_.map (_.keys (x), _.count), _.largest, 0)
values = _.map (values, function (v) {
return [v[0], v[1], ' '.repeats (max - v[0].length)] }) }
var square = !oneLine ? '[\n ]' : '[]'
var fig = !oneLine ? '{\n }' : '{ }'
return _.quoteWith (isArray ? square : fig, _.joinWith (oneLine ? ', ' : ',\n',
_.map (values, function (kv) {
return tabs + (isArray ? '' : (kv[0] + ': ' + (kv[2] || ''))) +
_.stringifyImpl (kv[1], parentsPlusX, siblings, depth + 1, cfg, indent) }))) }
else if (_.isDecimal (x) && (cfg.precision > 0)) {
return _.toFixed (x, cfg.precision) }
else {
return x + '' } } })
/* Safe version of toFixed
======================================================================== */
_.toFixed = function (x, precision) {
return (x && x.toFixed && x.toFixed (precision)) || undefined }
_.toFixed2 = function (x) {
return _.toFixed (x, 2) }
_.toFixed3 = function (x) {
return _.toFixed (x, 3) }
;
_.hasStdlib = true
/* _.throwsError
======================================================================== */
_.withTest (['stdlib', 'throwsError'], function () {
$assertThrows (
_.throwsError ('неуловимый Джо'),
_.matches ({ message: 'неуловимый Джо' })) }, function () { _.extend (_, {
throwsError: function (msg) {
return function () {
throw new Error (msg) }} }) })
_.overrideThis = _.throwsError ('override this')
_.notImplemented = _.throwsError ('not implemented')
/* A functional try/catch
======================================================================== */
_.deferTest (['stdlib', 'tryEval'], function () {
/* 'return' interface
*/
$assert ('ok', _.tryEval (_.constant ('ok'),
$fails))
$assert ('failed', _.tryEval (_.throwsError ('yo'),
$assertMatches.partial ({ message: 'yo'}).then (_.constant ('failed'))))
/* CPS interface
*/
$assertCPS (_.tryEval.partial (_.constant ('ok'),
_.constant ('failed')), 'ok')
$assertCPS (_.tryEval.partial (_.throwsError ('yo'),
_.constant ('failed')), 'failed')
}, function () { _.mixin ({
tryEval: function (try_, catch_, then_) { var result = undefined
try { result = try_ () }
catch (e) { result = catch_ && catch_ (e) }
return then_ ?