-
Notifications
You must be signed in to change notification settings - Fork 38
/
Underscore.cfc
2032 lines (1843 loc) · 66.8 KB
/
Underscore.cfc
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
/**
* @name Underscore.cfc
* @hint A port of Underscore.js for Coldfusion
* @introduction Underscore.cfc is a port of <a href="http://underscorejs.org">Underscore.js</a> for Coldfusion. It is a utility-belt library that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby). <br /><br />Underscore.cfc provides dozens of functions that support both the usual functional suspects: map, select, invoke - as well as more specialized helpers: function binding, sorting, deep equality testing, and so on. It delegates to built-in functions where applicable.<br /><br />Underscore.cfc is compatible with Adobe Coldfusion 10 and Railo 4.<br /><br />The project is <a href="http://github.com/russplaysguitar/underscorecf">hosted on GitHub</a>. Contributions are welcome.<br />
*/
component {
public any function init(obj = {}) {
this.obj = arguments.obj;
this.value = function() { return this.obj; };
// _ is referenced throughout this cfc
variables._ = this;
// Returns the same value that is used as the argument. In math: f(x) = x
// This function looks useless, but is used throughout UnderscoreCF as a default iterator.
_.identity = function(x) { return x; };
// for uniqueId
variables.counter = 1;
return this;
}
/* COLLECTION FUNCTIONS (ARRAYS, STRUCTURES, OR OBJECTS) */
/**
* @header _.each(collection, iterator, [context]) : void
* @hint Iterates over a collection of elements, yielding each in turn to an iterator function. The iterator is bound to the context object (component or struct), if one is passed. Each invocation of iterator is called with three arguments: (element, index, collection, this). If collection is an object/struct, iterator's arguments will be (value, key, collection, this).
* @example _.each([1, 2, 3], function(num){ writeDump(num); }); <br />=> dumps each number in turn... <br />_.each({one : 1, two : 2, three : 3}, function(num, key){ writeDump(num); });<br />=> dumps each number in turn...
*/
public void function each(obj = this.obj, iterator = _.identity, this = {}) {
if (isArray(arguments.obj)) {
var index = 1;
for (var element in arguments.obj) {
if (arrayIsDefined(arguments.obj, index)) {
iterator(element, index, arguments.obj, arguments.this);
}
index++;
}
}
else if (isObject(arguments.obj) || isStruct(arguments.obj) || isXmlNode(arguments.obj)) {
for (var key in arguments.obj) {
var val = arguments.obj[key];
iterator(val, key, arguments.obj, arguments.this);
}
}
else {
// query or something else? convert to array and recurse
_.each(toArray(arguments.obj), iterator, arguments.this);
}
}
/**
* @alias each
*/
public void function forEach(obj, iterator, this) {
_.each(argumentCollection = arguments);
}
/**
* @header _.map(collection, iterator, [context]) : array
* @hint Produces a new array of values by mapping each value in collection through a transformation function (iterator). If collection is an object/struct, iterator's arguments will be (value, key, collection, this).
* @example _.map([1, 2, 3], function(num){ return num * 3; }); <br />=> [3, 6, 9] <br />_.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; });<br />=> [3, 6, 9]
*/
public array function map(obj = this.obj, iterator = _.identity, this = {}) {
var result = [];
if (isArray(arguments.obj)) {
var index = 1;
var resultIndex = 1;
for (var element in arguments.obj) {
if (!arrayIsDefined(arguments.obj, index)) {
index++;
continue;
}
var local = {};
local.tmp = iterator(element, index, arguments.obj, arguments.this);
if (structKeyExists(local, "tmp")) {
result[resultIndex] = local.tmp;
}
index++;
resultIndex++;
}
}
else if (isObject(arguments.obj) || isStruct(arguments.obj) || isXmlNode(arguments.obj)) {
var index = 1;
for (var key in arguments.obj) {
var val = arguments.obj[key];
var local = {};
local.tmp = iterator(val, key, arguments.obj, arguments.this);
if (structKeyExists(local, "tmp")) {
result[index] = local.tmp;
}
index++;
}
}
else {
// query or something else? convert to array and recurse
result = _.map(toArray(arguments.obj), iterator, arguments.this);
}
return result;
}
/**
* @alias map
*/
public array function collect(obj, iterator, this) {
return _.map(argumentCollection = arguments);
}
/**
* @header _.reduce(collection, iterator, memo, [context]) : any
* @hint Also known as inject and foldl, reduce boils down a collection of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iterator.
* @example sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);<br />=> 6
*/
public any function reduce(obj = this.obj, iterator = _.identity, memo, this = {}) {
var outer = {};
if (structKeyExists(arguments, "memo")) {
outer.initial = memo;
}
_.each(arguments.obj, function(value, index, collection, this) {
if (!structKeyExists(outer, "initial")) {
memo = value;
outer.initial = true;
}
else {
memo = iterator(memo, value, index, this);
}
}, arguments.this);
return memo;
}
/**
* @alias reduce
*/
public any function foldl(obj, iterator, memo, this) {
return _.reduce(argumentCollection = arguments);
}
/**
* @alias reduce
*/
public any function inject(obj, iterator, memo, this) {
return _.reduce(argumentCollection = arguments);
}
/**
* @header _.reduceRight(collection, [iterator], memo, [context])
* @hint The right-associative version of reduce.
* @example list = [[0, 1], [2, 3], [4, 5]];<br />flat = _.reduceRight(list, function(a, b) { return _.concat(a, b); }, []);<br />=> [4, 5, 2, 3, 0, 1]
*/
public any function reduceRight(obj = this.obj, iterator = _.identity, memo, this = {}) {
var initial = structKeyExists(arguments, 'memo');
var reversed = _.reverse(_.toArray(arguments.obj));
if (!_.isEmpty(this) && !initial) {
iterator = _.bind(iterator, arguments.this);
}
return initial ? _.reduce(reversed, iterator, memo, arguments.this) : _.reduce(reversed, iterator);
}
// alias of reduceRight
public any function foldr(obj, iterator, memo, this) {
return _.reduceRight(argumentCollection = arguments);
}
/* ARRAY FUNCTIONS */
/**
* @header _.find(collection, iterator, [context]) : any
* @hint Looks through each value in the collection, returning the first one that passes a truth test (iterator). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire collection.
* @example even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });<br />=> 2
*/
public any function find(obj = this.obj, iterator = _.identity, this = {}) {
if (isArray(arguments.obj)) {
var index = 1;
for (var val in arguments.obj) {
if (iterator(val, index, arguments.obj, arguments.this)) {
return val;
break;
}
index++;
}
}
else if (isObject(arguments.obj) || isStruct(arguments.obj)) {
var index = 1;
for (var key in arguments.obj) {
var val = arguments.obj[key];
if (iterator(val, key, arguments.obj, arguments.this)) {
return val;
break;
}
index++;
}
}
else {
// query or something else? convert to array and recurse
return _.find(toArray(arguments.obj), iterator, arguments.this);
}
}
/**
* @alias find
*/
public any function detect(obj, iterator, this) {
return _.find(argumentCollection = arguments);
}
/**
* @header _.findWhere(collection, properties) : any
* @hint Looks through the collection and returns the first value that matches all of the key-value pairs listed in properties.
* @example _.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});<br />=> {year: 1918, newsroom: "The New York Times",<br /> reason: "For its public service in publishing in full so many official reports,<br /> documents and speeches by European statesmen relating to the progress and<br /> conduct of the war."}
*/
public any function findWhere(obj = this.obj, required attrs) {
if (_.isEmpty(attrs)) return [];
return _.find(obj, function(value) {
for (var key in attrs) {
if (attrs[key] != value[key]) return false;
}
return true;
});
}
/**
* @header _.filter(collection, iterator, [context]) : array
* @hint Looks through each value in the collection, returning an array of all the values that pass a truth test (iterator).
* @example evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });<br />=> [2, 4, 6]
*/
public array function filter(obj = this.obj, iterator = _.identity, this = {}) {
var result = [];
if (isArray(arguments.obj)) {
var index = 1;
var resultIndex = 1;
for (var val in arguments.obj) {
var success = iterator(val, index, arguments.obj, arguments.this);
if (success) {
result[resultIndex] = val;
resultIndex++;
}
index++;
}
}
else if (isObject(arguments.obj) || isStruct(arguments.obj)) {
var index = 1;
var resultIndex = 1;
for (var key in arguments.obj) {
var val = arguments.obj[key];
var success = iterator(val, key, arguments.obj, arguments.this);
if (success) {
result[resultIndex] = val;
resultIndex++;
}
index++;
}
}
else {
// query or something else? convert to array and recurse
return _.filter(toArray(arguments.obj), iterator, arguments.this);
}
return result;
}
/**
* @alias filter
*/
public array function select(obj, iterator, this) {
return _.filter(argumentCollection = arguments);
}
/**
* @header _.reject(collection, iterator, [context]) : array
* @hint Returns the values in collection without the elements that the truth test (iterator) passes. The opposite of filter.
* @example odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });<br />=> [1, 3, 5]
*/
public array function reject(obj = this.obj, iterator = _.identity, this = {}) {
var result = [];
if (isArray(arguments.obj)) {
var index = 1;
var resultIndex = 1;
for (var val in arguments.obj) {
var success = iterator(val, index, arguments.obj, arguments.this);
if (!success) {
result[resultIndex] = val;
resultIndex++;
}
index++;
}
}
else if (isObject(arguments.obj) || isStruct(arguments.obj)) {
var index = 1;
var resultIndex = 1;
for (var key in arguments.obj) {
var val = arguments.obj[key];
var success = iterator(val, key, arguments.obj, arguments.this);
if (!success) {
result[resultIndex] = val;
resultIndex++;
}
index++;
}
}
else {
// query or something else? convert to array and recurse
return _.reject(toArray(arguments.obj), iterator, arguments.this);
}
return result;
}
/**
* @header _.all(collection, iterator, [context]) : boolean
* @hint Returns true if all of the values in the collection pass the iterator truth test.
* @example _.all([true, 1, 'no'], _.identity);<br />=> false
*/
public boolean function all(obj = this.obj, iterator = _.identity, this = {}) {
var result = false;
if (isArray(arguments.obj)) {
var index = 1;
for (var val in arguments.obj) {
result = iterator(val, index, arguments.obj, arguments.this);
if (!result) {
break;
}
index++;
}
if (arrayLen(arguments.obj) == 0) {
result = true;
}
}
else if (isObject(arguments.obj) || isStruct(arguments.obj)) {
var index = 1;
for (var key in arguments.obj) {
var val = arguments.obj[key];
result = iterator(val, key, arguments.obj, arguments.this);
if (!result) {
break;
}
index++;
}
}
else {
return _.all(toArray(arguments.obj), iterator, arguments.this);
}
return toBoolean(result);
}
/**
* @alias all
*/
public boolean function every(obj, iterator, this) {
return _.all(argumentCollection = arguments);
}
/**
* @header _.any(collection, [iterator], [context]) : boolean
* @hint Returns true if any of the values in the collection pass the iterator truth test. Short-circuits and stops traversing the collection if a true element is found.
* @example _.any([0, 'yes', false]);<br />=> true
*/
public boolean function any(obj = this.obj, iterator = _.identity, this = {}) {
var result = false;
if (isArray(arguments.obj)) {
var index = 1;
for (var value in arguments.obj) {
result = iterator(value, index, arguments.obj, arguments.this);
if (result) {
break;
}
index++;
}
}
else if (isObject(arguments.obj) || isStruct(arguments.obj)) {
var index = 1;
for (var key in arguments.obj) {
var value = arguments.obj[key];
result = iterator(value, key, arguments.obj, arguments.this);
if (result) {
break;
}
index++;
}
}
else {
return _.any(toArray(arguments.obj), iterator, arguments.this);
}
return toBoolean(result);
}
/**
* @alias any
*/
public boolean function some(obj, iterator, this) {
return _.any(argumentCollection = arguments);
}
/**
* @header _.include(collection, value) : boolean
* @hint Returns true if the value is present in the collection.
* @example _.include([1, 2, 3], 3);<br />=> true
*/
public boolean function include(obj = this.obj, target) {
return _.any(arguments.obj, function(value) {
return isEqual(value, target);
});
}
/**
* @header _.invoke(collection, methodName, [arguments]) : array
* @hint Calls the method named by methodName on each value in the collection. The arguments struct passed to invoke will be forwarded on to the method invocation.
* @example _.invoke([{fun: function(){ return 1; }}], 'fun');<br />=> [1]
*/
public array function invoke(obj = this.obj, method, args = {}) {
return _.map(arguments.obj, function(value) {
if (_.isFunction(method)) {
// try to call method() directly
var result = method(value, args);
if (!isNull(result)) {
return result;
}
else {
return value;
}
}
else if((isObject(value) || isStruct(value)) && structKeyExists(value, method)) {
// call method as member of obj item
var fun = value[method];
return fun(value, args);
}
else {
// no idea what method() is all about, return value instead
// note: this might be dangerous
return value;
}
});
}
/**
* @header _.pluck(collection, propertyName) : array
* @hint A convenient version of what is perhaps the most common use-case for map: extracting a collection of property values.
* @example stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];<br />_.pluck(stooges, 'name');<br />=> ["moe", "larry", "curly"]
*/
public array function pluck(obj = this.obj, key) {
return _.map(arguments.obj, function(value){
if (_.isFunction(key)) {
return key(value);
}
else if (isArray(value) && arrayLen(value) >= key) {
return value[key];
}
else if ((isStruct(value) || isObject(value)) && structKeyExists(value, key)) {
return value[key];
}
else if (isQuery(value)) {
return _.pluck(_.toArray(value), key);
}
else {
return;
}
});
}
/**
* @header _.where(list, properties) : array
* @hint Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.
* @example _.where(listOfPlays, {author: "Shakespeare", year: 1611});<br />=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},<br /> {title: "The Tempest", author: "Shakespeare", year: 1611}]
*/
public array function where(obj = this.obj, required attrs) {
if (_.isEmpty(attrs)) return [];
return _.filter(obj, function(value) {
for (var key in attrs) {
if (!structKeyExists(value, key) || attrs[key] != value[key]) return false;
}
return true;
});
}
/**
* @header _.max(collection, [iterator], [context]) : any
* @hint Returns the maximum value in collection. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.
* @example stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];<br />_.max(stooges, function(stooge){ return stooge.age; });<br />=> {name : 'curly', age : 60};
*/
public any function max(obj = this.obj, iterator = _.identity, this = {}) {
var result = {};
_.each(arguments.obj, function(value, index, obj, this) {
var computed = iterator(value, index, obj, this);
if (isNumeric(computed)) {
if (!structKeyExists(result, 'computed') || computed >= result.computed) {
result = {value : value, computed : computed};
}
}
}, arguments.this);
if (structKeyExists(result, 'value')) {
return result.value;
}
}
/**
* @header _.min(collection, [iterator], [context]) : any
* @hint Returns the minimum value in collection. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.
* @example numbers = [10, 5, 100, 2, 1000];<br />_.min(numbers);<br />=> 2
*/
public any function min(obj = this.obj, iterator = _.identity, this = {}) {
var result = {};
_.each(arguments.obj, function(value, index, obj, this) {
var computed = iterator(value, index, obj, this);
if (isNumeric(computed)) {
if (!structKeyExists(result, 'computed') || computed <= result.computed) {
result = {value : value, computed : computed};
}
}
}, arguments.this);
if (structKeyExists(result, 'value')) {
return result.value;
}
}
/**
* @header _.sortBy(collection, [iterator], [context]) : array
* @hint Returns a sorted copy of collection, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the object key to sort by. Delegates to arraySort().
* @example _.sortBy([6, 2, 4, 3, 5, 1], function(num){ return num; });<br />=> [1, 2, 3, 4, 5, 6]
*/
public array function sortBy(obj = this.obj, val, this = {}) {
if (!structKeyExists(arguments, 'val')) {
var iterator = _.identity;
}
else if (_.isFunction(val)) {
var iterator = val;
}
else {
var iterator = function(obj) {
return obj[val];
};
}
var result = _.map(arguments.obj, function(value, index, collection, this) {
return {
value : value,
criteria : iterator(value, index, collection, arguments.this)
};
}, arguments.this);
arraySort(result, function(left, right) {
if (!structKeyExists(left, 'criteria')) {
return 1;
}
else if (!structKeyExists(right, 'criteria')) {
return -1;
}
var a = left.criteria;
var b = right.criteria;
return _.comparison(a, b);
});
return _.pluck(result, 'value');
}
// default comparator for merge()
public numeric function comparison(left, right) {
if(!isSimpleValue(left) || !isSimpleValue(right))
return 0;// can't compare non-simple values
else if(left == right)
return 0;
else if(left < right)
return -1;
else
return 1;
}
// An internal function used for aggregate "group by" operations.
private struct function group(obj = this.obj, value = _.identity, this = {}, required behavior) {
var result = {};
if (_.isFunction(value)) {
var iterator = value;
}
else {
var iterator = function(obj) { return obj[value]; };
}
_.each(arguments.obj, function(val, index, obj, this) {
behavior(result, iterator(val, index, obj, this), val);
});
return result;
}
/**
* @header _.groupBy(collection, iterator) : struct
* @hint Splits a collection into sets, grouped by the result of running each value through iterator. If iterator is a string instead of a function, groups by the property named by iterator on each of the values.
* @example _.groupBy([1.3, 2.1, 2.4], function(num){ return fix(num); });<br />=> {1: [1.3], 2: [2.1, 2.4]}<br /><br />_.groupBy(['one', 'two', 'three'], function(num) { return len(num); });<br />=> {3: ["one", "two"], 5: ["three"]}
*/
public struct function groupBy(obj = this.obj, val) {
var result = {};
if (_.isFunction(val)) {
var iterator = val;
}
else {
var iterator = function(obj) { return obj[val]; };
}
_.each(arguments.obj, function(value, index) {
var key = iterator(value, index);
if (!structKeyExists(result, key)) {
result[key] = [];
}
arrayAppend(result[key], value);
});
return result;
}
/**
* @header _.indexBy(collection, iterator) : struct
* @hint Indexes the object's values by a criterion, similar to `groupBy`, but for when you know that your index values will be unique.
* @example var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}]; _.indexBy(stooges, 'age'); => { "40": {name: 'moe', age: 40}, "50": {name: 'larry', age: 50}, "60": {name: 'curly', age: 60} }
*/
public struct function indexBy(obj = this.obj, val) {
var result = {};
if (_.isFunction(val)) {
var iterator = val;
}
else {
var iterator = function(obj) { return obj[val]; };
}
_.each(arguments.obj, function(value, index) {
var key = iterator(value, index);
result[key] = value;
});
return result;
}
/**
* @header _.countBy(collection, iterator) : struct
* @hint Sorts a collection into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* @example _.countBy([1, 2, 3, 4, 5], function(num) { return num % 2 == 0 ? 'even' : 'odd'; });<br />=> {odd: 3, even: 2}
*/
public any function countBy(obj = this.obj, value, this = {}) {
return group(obj, value, this, function(required result, key, value) {
var k = isNull(arguments.key) ? "" : arguments.key;
if (!_.has(result, k)) result[k] = 0;
result[k]++;
});
}
/**
* @header _.sortedIndex(collection, value, [iterator]) : numeric
* @hint Uses a binary search to determine the index at which the value should be inserted into the collection in order to maintain the collection's sorted order. If an iterator is passed, it will be used to compute the sort ranking of each value.
* @example _.sortedIndex([10, 20, 30, 40, 50], 35);<br />=> 4
*/
public numeric function sortedIndex(array = this.obj, obj, iterator = _.identity) {
var low = 0;
var high = arrayLen(array);
while (low < high) {
var mid = BitSHRN((low + high), 1);
if (iterator(array[mid]) < iterator(arguments.obj) ) {
low = mid + 1;
}
else {
high = mid;
}
}
return low;
}
/**
* @header _.shuffle(array) : array
* @hint Returns a shuffled copy of the array, using a version of the Fisher-Yates shuffle.
* @example _.shuffle([1, 2, 3, 4, 5, 6]);<br />=> [4, 1, 6, 3, 5, 2]
*/
public array function shuffle(obj = this.obj) {
var shuffled = duplicate(arguments.obj);
var rand = 0;
_.each(shuffled, function(value, index, collection) {
rand = fix(1 + (rand() * (index)));
shuffled[index] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
}
/**
* @header _.toArray(collection) : array
* @hint Converts the collection (object, struct, query, xml, or cf-list), into an array.
* @example _.toArray({a:10,b:20});<br />=> [10, 20]
*/
public array function toArray(obj = this.obj) {
if (isArray(arguments.obj)) {
return duplicate(arguments.obj);
}
else if ((isStruct(arguments.obj) || isObject(arguments.obj)) && structKeyExists(arguments.obj, "toArray") && isClosure(arguments.obj.toArray)) {
return arguments.obj.toArray();
}
else if (isQuery(arguments.obj)) {
var result = [];
for (var index = 1; index <= arguments.obj.RecordCount; index++) {
var row = {};
for (var colName in listToArray(arguments.obj.columnList)) {
row[colName] = arguments.obj[colName][index];
}
result[index] = row;
}
return result;
}
else if (isXmlNode(arguments.obj)) {
var xmlToArray = function (xml) {
return _.map(xml.xmlChildren, function (node) {
if (!_.size(node.xmlChildren))
return node.xmlText;
else
return xmlToArray(node.xmlChildren);
});
};
var result = [];
_.each(arguments.obj, function (node) {
arrayAppend(result, xmlToArray(node), true);
});
return result;
}
else if (isObject(arguments.obj) || isStruct(arguments.obj)) {
return _.values(arguments.obj);
}
else if (_.isString(arguments.obj)) {
return listToArray(arguments.obj, ',', true);
}
else
{
return [arguments.obj];
}
}
/**
* @header _.toQuery(array, [columnNames], [columnTypes]) : query
* @hint Converts an array of structs to a Coldfusion query. Columns are created dynamically unless a comma-delimited list of column names are provided. Column types are "varchar" unless a comma-delimited list of column types is provided. Delegates to native QueryNew().
* @example _.toQuery([{someColumn: "row 1"}]); <br />=> (result is a query with one column titled "someColumn" and one row containing "row 1"
*/
public query function toQuery(array array = this.obj, string columnNames, string columnTypes) {
if (!ArrayLen(array)) return QueryNew("");
if (isNull(arguments.columnNames)) {
var colsArray = _.reduce(arguments.array, function (memo, struct) {
return _.union(memo, _.keys(struct));
}, []);
arguments.columnNames = _.join(colsArray, ",");
}
if (isNull(arguments.columnTypes)) {
var typesArray = _.map(_.toArray(arguments.columnNames), function () { return "varchar"; });
arguments.columnTypes = _.join(typesArray, ",");
}
return QueryNew(arguments.columnNames, arguments.columnTypes, arguments.array);
}
/**
* @header _.toXml(collection, [*elementNames]) : xml
* @hint Converts a collection to an XML object. Element names default to variable types. If provided, element names will be assigned to unnamed elements (any element without a key) in the order they are listed.
* @example _.toXml([1, 2]); <br />=> <array><element>1</element><element>2</element></array> <br /><br />_.toXml([3], 'myArray', 'number'); <br />=> <myArray><number>3</number><myArray>
*/
public xml function toXml(obj = this.obj) {
var toXmlString = function(required any obj, array elementNames = []) {
var xmlString = '';
var elementName = '';
var isArray = isArray(arguments.obj);
var isQuery = isQuery(arguments.obj);
if (_.size(arguments.elementNames) > 0)
elementName = _.first(arguments.elementNames);
else if (isArray)
elementName = 'array';
else if (isQuery)
elementName = 'query';
else if (isObject(arguments.obj))
elementName = 'object';
else if (isStruct(arguments.obj))
elementName = 'struct';
else
elementName = 'element';
xmlString &= '<' & elementName & '>';
if (isSimpleValue(arguments.obj) || _.isFunction(arguments.obj)) {
xmlString &= _.result(arguments, 'obj');
}
else {
var remainingNames = _.rest(arguments.elementNames);
_.each(arguments.obj, function (val, key) {
if (!isArray && !isQuery)
remainingNames = _.concat([key], remainingNames);// key is el name for non-array, non-query types
xmlString &= toXmlString(val, remainingNames);
});
}
xmlString &= '</' & elementName & '>';
return xmlString;
};
var elementNames = _.slice(arguments, 2);
var xmlString = toXmlString(arguments.obj, elementNames);
return xmlParse(xmlString);
}
/**
* @header _.size(collection) : numeric
* @hint Return the number of values in the collection. Note: A simple value will be considered a single list item.
* @example _.size({one : 1, two : 2, three : 3});<br />=> 3<br />_.size(99);<br />=> 1<br />_.size("101");<br />=> 1<br />_.size();<br />=> 0
*/
public numeric function size(obj = this.obj) {
if (isObject(arguments.obj) || isStruct(arguments.obj)) {
return structCount(arguments.obj);
}
else if (isArray(arguments.obj)) {
return arrayLen(arguments.obj);
}
else if (isQuery(arguments.obj)) {
return arguments.obj.recordCount;
}
else if (isSimpleValue(arguments.obj)) {
return arrayLen(listToArray(arguments.obj));
}
else {
throw("size() is only compatible with objects, structs, queries, arrays, and comma-delimeted lists.", "Underscore");
}
}
/* ARRAY FUNCTIONS */
/**
* @header _.first(array, [n]) : any
* @hint Returns the first element of an array. Passing n will return the first n elements of the array.
* @example _.first([5, 4, 3, 2, 1]);<br />=> 5
*/
public any function first(array array = this.obj, n, guard = false) {
if (structKeyExists(arguments, 'n') && !guard) {
return _.slice(array, 1, n);
}
else {
return array[1];
}
}
/**
* @alias first
*/
public any function head(array, n, guard) {
return _.first(argumentCollection = arguments);
}
/**
* @alias first
*/
public any function take(array, n, guard) {
return _.first(argumentCollection = arguments);
}
/**
* @header _.slice(array, [from], [to]) : array
* @hint Returns a subsection of the array. Negative values for to and from offset from the end of the array.
* @example _.slice([1, 2, 3, 4]);<br/>=> [2, 3, 4]<br/><br/>_.slice([1, 2, 3, 4], 3);<br/>=> [3, 4]<br/><br/>_.slice([1, 2, 3, 4], 2, -1);<br/>=> [2, 3]<br/><br/>_.slice([1, 2, 3, 4], -3, -1);<br/>=> [2, 3]
*/
public any function slice(array = [], numeric from = 2, numeric to) {
var len = arrayLen(array);
to = (!structKeyExists(arguments, 'to')) ? len + 1 :
(to > (len + 1)) ? len + 1 :
(to < 0) ? to + len + 1 :
to + 1;
from = (from > 0) ? from :
(from < 0) ? from + len + 1 :
0;
if (from == 0){ throw("CF Arrays start with index 1", "Underscore"); }
var sliceLen = arguments.to - arguments.from;
if (sliceLen <= 0){ return []; }
return arraySlice(array, from, sliceLen);
}
/**
* @header _.initial(array, [n]) : array
* @hint Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result. Note: CF arrays start at an index of 1
* @example _.initial([5, 4, 3, 2, 1]);<br />=> [5, 4, 3, 2]
*/
public array function initial(array array = this.obj, n = 1, guard = false) {
if (guard) {
var exclude = 1;
}
else {
var exclude = n;
}
return _.slice(array, 1, arrayLen(array) - exclude);
}
/**
* @header _.last(array, [n]) : any
* @hint Returns the last element of an array. Passing n will return the last n elements of the array.
* @example _.last([5, 4, 3, 2, 1]);<br />=> 1
*/
public any function last(array array = this.obj, n, guard = false) {
if (structKeyExists(arguments,'n') && !guard) {
return _.slice(array, max(ArrayLen(array) - n + 1, 1));
} else if (arrayLen(array)) {
return array[ArrayLen(array)];
}
else {
return JavaCast("null", 0);
}
}
/**
* @header _.rest(array, [index]) : array
* @hint Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.
* @example _.rest([5, 4, 3, 2, 1]);<br />=> [4, 3, 2, 1]
*/
public array function rest(array array = this.obj, index = 2, guard = false) {
if (guard) {
index = 1;
}
return _.slice(array, index);
}
/**
* @alias rest
*/
public array function tail(array, index, guard) {
return _.rest(argumentCollection = arguments);
}
/**
* @alias rest
*/
public array function drop(array, index, guard) {
return _.rest(argumentCollection = arguments);
}
/**
* @header _.compact(array) : array
* @hint Returns a copy of the array with all falsy values removed. In Coldfusion, false, 0, and "" are all falsy.
* @example _.compact([0, 1, false, 2, '', 3]);<br />=> [1, 2, 3]
*/
public array function compact(array array = this.obj) {
return _.filter(array, function(value){
return val(value);
});
}
/**
* @header _.flatten(array, [shallow]) : array
* @hint Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.
* @example _.flatten([1, [2], [3, [[4]]]]);<br />=> [1, 2, 3, 4];<br /><br />_.flatten([1, [2], [3, [[4]]]], true);<br />=> [1, 2, 3, [[4]]];
*/
public array function flatten(array array = this.obj, shallow = false) {
return _.reduce(array, function(memo, value) {
if (isArray(value)) {
if (shallow) {
memo = _.concat(memo, value);
}
else {
memo = _.concat(memo, _.flatten(value));
}
}
else {
var index = arrayLen(memo) + 1;
memo[index] = value;
}
return memo;
}, []);
}
/**
* @header _.concat(*arrays) : array
* @hint Concatenates any number of arrays together an returns the result. Delegates to ArrayAppend().
* @example _.concat([1, 2, 3], [4, 5, 6]);<br />=> [1, 2, 3, 4, 5, 6];
*/
public array function concat() {
var numArgs = _.size(arguments);
var result = [];
for(var i = 1; i <= numArgs; i++) {
if (!isArray(arguments[i])) {
throw("Cannot concat() non-array collections", "Underscore");
}
ArrayAppend(result, arguments[i], true);
}
return result;
}
/**
* @header _.reverse(array) : array
* @hint Returns a copy of the array in reverse order.
* @example _.reverse([1, 2, 3]);<br />=> [3, 2, 1]
*/
public array function reverse(array obj = this.obj) {
var result = [];