-
Notifications
You must be signed in to change notification settings - Fork 2
/
PowerArray.js
1863 lines (1713 loc) · 80 KB
/
PowerArray.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
'use strict';
var mainContainer, module = module || undefined, isModule = false, isBrowser = true;
if (typeof module !== "undefined") {
module.exports = {};
isModule = true;
}
if (typeof window === 'object') {
mainContainer = window;
} else {
isBrowser = false;
mainContainer = global;
}
if (mainContainer.pa && console && console.warn) {
console.warn('PowerArray => Cannot load, global variable "pa" already exists. Assuming that pa is already loaded => Trusting older instance');
} else {
mainContainer.PowerArray = mainContainer.pa = function (object) {
if (object.constructor === Array || object.paIsArray) {
return new paArray(object);
} else {
//console.warn('PowerArray => The passed object is not natively an array. Trying to handle it as an array-like object...')
if (
((mainContainer.ol !== undefined && ol.Collection) && object instanceof ol.Collection) || /** Detect openlayers collections created without modules (old versions) */
(typeof object.getArray === 'function')) /** Detect openlayers collections created with modules (newer versions) */ {
return paArray(object.getArray());
}
if (object.length === undefined) {
throw new Error('PowerArray => The passed object is not an array, or usable as such.');
}
return new paArray(object);
}
};
pa.mainContainer = mainContainer; //pa.mainContainer is a reference to the top element containing the application (window by browsers, global by Node);
/*functions directly bound to the pa object: */
mainContainer.pa.Range = function (from, to, step) {
if (!pa.IsNumeric(from)) {
throw new Error('PowerArray => Range fuction => The parameter "from" must be numeric. Wrong value is "' + from + '"');
}
if (!pa.IsNumeric(to)) {
throw new Error('PowerArray => Range fuction => The parameter "to" must be numeric. Received value is "' + to + '"');
}
if (!pa.IsNumeric(step)) {
throw new Error('PowerArray => Range fuction => The parameter "step" must be numeric. Received value is "' + step + '"');
}
from = parseFloat(from);
to = parseFloat(to);
step = parseFloat(step);
var result = [], i, l, currVal = from;
while (currVal < to) {
result.push(currVal);
currVal += step;
}
result.push(to);
return result;
};
mainContainer.pa.config = {
defaults: {
defaultPromiseTimeout: 10000
}
};
mainContainer.pa.utils = {}
mainContainer.pa.utils = {
DataTypes: {
String: 'String',
Number: 'Number',
Date: 'Date',
Boolean: 'Boolean',
Object: 'Object',
ArrayOfObjects: 'ArrayOfObjects',
ArrayOfPrimitives: 'ArrayOfPrimitives',
RegExp: 'RegExp',
Function: 'Function',
Null: 'Null',
Undefined: 'Undefined'
},
IsArrayOfObjects: function (val) {
var l;
if (!val.paIsArray || val.length === undefined) {
return false;
}
l = val.length;
while (l--) {
//TODO: this could fail in collections having objects but one undefined
if (pa.utils.GetTypeOf(val[l]) !== pa.utils.DataTypes.Object) {
return false;
}
}
return true;
},
AreWhereConditionsObjectsEqual: function (a, b) {
if (pa.utils.isNullEmptyOrUndefined(a) && pa.utils.isNullEmptyOrUndefined(b)) return true; //if both are undefined, null, or empty, return a true.
var comparableA = pa.utils.GetComparableConditionsObject(a);
var comparableB = pa.utils.GetComparableConditionsObject(b);
return pa.utils.Equals(comparableA, comparableB, false, false);
},
GetWCOFunctionValueHash: function (func) {
let result = func.paParams.name + "(";
if (func.paParams) {
result += mainContainer.pa.utils.ArgumentsToArray(func.paParams)
.RunEach((param) => {
if (param === undefined) {
return '?und';
}
return param.toString();
}, false, true).join(',');
} else {
console.warn("PowerArray => GetWCOFunctionValueHash received a function that were not normalized (missing paParams). This is not necessary a problem, if you know why it is like that!")
result = func.toString();
}
return result + ")";
},
GetComparableConditionsObject: function (wco) {
var result = {};
function iterate(obj, dest) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
switch (typeof obj[property]) {
case "object":
dest[property] = {};
iterate(obj[property], dest[property]);
break;
case "function":
dest[property] = mainContainer.pa.utils.GetWCOFunctionValueHash(obj[property]);
break;
default:
dest[property] = obj[property];
}
}
}
}
for (var property in wco) {
if (wco.hasOwnProperty(property)) {
switch (typeof wco[property]) {
case "object":
result[property] = {};
iterate(wco[property], result[property]);
break;
case "function":
result[property] = mainContainer.pa.utils.GetWCOFunctionValueHash(wco[property]);
break;
default:
result[property] = wco[property];
}
}
}
return result;
},
/**
* Parses a string to boolean value. This function searches strictly for the strings "true", "True", "trUE", "falsE", etc.
* @param str the string to be evaluated
* @param throwIfNotMatch Boolean, if true, an exception will be raised if the string does not match. If false, null will be returned
* @returns {*} boolean value if string matches, null if not
*/
parseBoolean: function (str, throwIfNotMatch) {
if (!pa.utils.isNullEmptyOrUndefined(str)) {
var strU = str.toUpperCase();
if (strU === "TRUE") {
return true;
}
if (strU === "FALSE") {
return false;
}
}
if (throwIfNotMatch) {
throw new Error("The string passed to function parseBoolean (" + str + ") doesn't match with any valid string");
}
return null;
}, /**
* evaluate if something is empty. Deppending on the passed object what it exactly search for:
* Numbers and Strings are evaluated against "", undefined and Null
* Objects having at least one own property returns false (also if the property is empty!)
* Arrays returns false if his length is > 0 or "what" is a function
*
* @param what the element to evaluate
* @returns {boolean}
*/
isNullEmptyOrUndefined: function (what) {
// null has to be evaluated before checking typeof
if (what === null || what === undefined || what === '') {
return true;
}
var t = typeof what;
switch (t) {
case "boolean":
case "function":
return false;
}
//Array
if (what.paIsArray && what.length > 0)
return false;
//Object
if (t === 'object') {
var count = 0;
for (var p in what) {
if (what.hasOwnProperty(p))
return false;
}
return true;
}
if (t === "number" && what === 0) {
return false;
}
if (!what) {
return true;
}
return (what + "").length === 0;
},
/**
* Copy properties from a source object to a destination object
* @param {Object} source source object
* @param {Object} dest destination object
* @param {Array<String>} propsList list of properties to copy. if falsy is passed, all properties will be copied.
* @param {boolean} excludeEmptyProps avoid the copy of empty props to the target
* @param {boolean} ignoreEmptyProps
* @returns {}
*/
CopyObjectProps: function (source, dest, propsList, excludeEmptyProps, nullOrUndefinedAsEmptyString) {
if (!propsList) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (nullOrUndefinedAsEmptyString) {
var sourceProp = source[prop]
dest[prop] = (pa.utils.isNullEmptyOrUndefined(sourceProp)) ? '' : sourceProp;
} else {
if (excludeEmptyProps && pa.utils.isNullEmptyOrUndefined(source[prop])) {
continue;
}
dest[prop] = source[prop];
}
}
}
} else {
propsList.RunEach(function (prop) {
if (nullOrUndefinedAsEmptyString) {
var sourceProp = source[prop]
dest[prop] = (pa.utils.isNullEmptyOrUndefined(sourceProp)) ? '' : sourceProp;
} else {
if (excludeEmptyProps && pa.utils.isNullEmptyOrUndefined(source[prop])) {
return;
}
dest[prop] = source[prop];
}
});
}
},
Equals: function (a, b, enforce_properties_order, cyclic) {
return mainContainer.pa.paWhereHelper.equals(a, b, enforce_properties_order, cyclic);
},
GetTypeOf: function (element, analyzeData) {
if (element === null) {
return pa.utils.DataTypes.Null;
}
if (element === undefined) {
return pa.utils.DataTypes.Undefined;
}
var to = typeof element;
switch (to) {
case 'string':
return pa.utils.DataTypes.String;
case 'function':
return pa.utils.DataTypes.Function;
case 'number':
return pa.utils.DataTypes.Number;
case 'boolean':
return pa.utils.DataTypes.Boolean;
case 'object':
//check hidden types
if (element instanceof String) {
return pa.utils.DataTypes.String;
}
if (element instanceof Date) {
return pa.utils.DataTypes.Date;
}
if (element instanceof Number) {
return pa.utils.DataTypes.Number;
}
if (element instanceof RegExp) {
return pa.utils.DataTypes.RegExp;
}
if (element.paIsArray) {
// If its an array of objects, it has to be handled different,
if (analyzeData && pa.utils.IsArrayOfObjects(element)) {
return pa.utils.DataTypes.ArrayOfObjects;
} else {
return pa.utils.DataTypes.ArrayOfPrimitives;
}
}
return pa.utils.DataTypes.Object;
default:
//any others
throw new Error("PowerArray Error : Unknown Datatype!");
}
},
ArgumentsToArray: function (args, from, to) {
var i = from | 0, l = to || args.length, result = [];
for (; i < l; i++) {
result.push(args[i]);
}
return result;
},
/**
* Generates a guid-like string
* @param {*} prefix
* @param {*} sufix
* @param {string} separator character between guid char blocks
*/
GenerateUuid: function (prefix, sufix, separator) {
let localSeparator = (separator === undefined) ? '-' : separator;
function getRandom4Chars() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return ((prefix !== undefined) ? prefix + localSeparator : '') +
getRandom4Chars() + getRandom4Chars() +
localSeparator + getRandom4Chars() + localSeparator + getRandom4Chars() +
localSeparator + getRandom4Chars() + localSeparator + getRandom4Chars() + getRandom4Chars() + getRandom4Chars() +
((sufix !== undefined) ? localSeparator + sufix : '');
},
/**
* Generates a guid-like string
* @param {string} separator character between guid char blocks
*/
GenerateGuid: function (separator) {
let localSeparator = separator === undefined ? '-' : separator;
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() +
localSeparator + s4() + localSeparator + s4() +
localSeparator + s4() + localSeparator + s4() + s4() + s4();
},
PropsToArray: function (obj, valueProcessor) {
var result = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
result.push({ property: prop, value: (valueProcessor) ? valueProcessor(obj[prop]) : obj[prop] });
}
}
return result;
}
};
mainContainer.pa.paEachParalellsHelper = {
CheckParalellTaskStates: function (paralellId) {
var paralell = mainContainer.pa.paEachParalellsHelper.currentParalellIds[paralellId];
return paralell.CompletedTasks === paralell.TotalProcesses;
},
currentParalellIds: {},
actionKeys: {
Runeach: 'RunEach',
TaskState: 'TaskState'
},
eventKeys: {
RuneachDone: 'RuneachDone',
TaskState: 'TaskStateResponse'
}
};
mainContainer.pa.paWhereHelper = {
FillConditions: function (item, conditions) {
var l = conditions.length, condition, result, subArray;
while (l--) {
condition = conditions[l];
//conditions can be functions or single values, if there are single values, they have to ve evaluated by
//===. if they are functions everything should continue as by default
if (typeof condition.condition !== 'function') {
//if the condition is an object, it's necessary to handle it different.
//If that's the case we start internally another Where() call, but we know that we are
//evaluating pro Where call just ONE item and it could be very expensive. TODO: optimize this somehow!
if (mainContainer.pa.utils.GetTypeOf(condition.condition) === mainContainer.pa.utils.DataTypes.Object) {
var itemType = mainContainer.pa.utils.GetTypeOf(item[condition.column], true);
switch (itemType) {
case mainContainer.pa.utils.DataTypes.ArrayOfObjects:
case mainContainer.pa.utils.DataTypes.ArrayOfPrimitives:
result = item[condition.column].Where.call(item[condition.column], condition.condition, false, true);
//when sending true als "justFirst", Where() will return the first found element, not an array,
//because i'm sending true for performance reasons, it's necessary to evaluate the result with undefined
//instead of: "return result.length > 0;" it's now "return result !== undefined;"
if (result !== undefined) {
continue;
} else {
return false;
}
case mainContainer.pa.utils.DataTypes.Object:
subArray = pa([item[condition.column]]);
result = subArray.Where.call(subArray, condition.condition, false, true);
if (result !== undefined) {//See previous comment about justFirst param
continue;
} else {
return false;
}
}
}
condition.condition = pa.EqualTo3(condition.condition); //transforms an explicit value into an === evaluation
}
const valueToEvaluate = condition.column ? item[condition.column] : item;
if (!item || !condition.condition(valueToEvaluate)) { //if one condition is not fulfilled, just return false;
return false;
}
}
return true;
},
ProcessConditionObject: function (whereConditions, keepOrder, isArrayOfConditions, justFirst, justIndexes) {
//to call this function, "this" should be an array!
var fc = mainContainer.pa.paWhereHelper.FillConditions,
i, w, item, lw, assert, l, result = [], realConditionsArr = [];
if (!isArrayOfConditions) {
//whereConditions is not an array, but i need it in that form
whereConditions = [whereConditions];
}
//Where conditions must be processed in order
for (i = 0, l = whereConditions.length; i < l; i++) {
var whereConditionObject = whereConditions[i], realConditions = [];
if (typeof whereConditionObject === 'function') {
realConditions.push({
column: property,
condition: whereConditionObject
});
} else {
for (var property in whereConditionObject) {
if (whereConditionObject.hasOwnProperty(property)) {
//transform the keys into a better object with properties Column and Condition
//if whereConditionObject[property] is an array, that means that its a multi filter for a single column, for example: array.Where({age : [GreatherThan(33), BiggerThan(21)], otherField : '33' });
if (whereConditionObject[property] && whereConditionObject[property].paIsArray) {
/** MULTIPLE CONDITIONS FOR A SINGLE PROPERTY. Pushed on the realconditions as an AND **/
whereConditionObject[property].RunEach(function (subCondition) {
realConditions.push({
column: property,
condition: subCondition
});
});
} else {
realConditions.push({
column: property,
condition: whereConditionObject[property]
});
}
}
}
}
realConditionsArr.push(realConditions);
//whereConditionObject.realConditions = realConditions; //attach the result of this loop direct to the whereConditionObject
}
//Real conditions stored
l = this.length;
if (keepOrder) { //Anti DRY pattern ;( but as long as it still being small will continue this way to improve performance
for (i = 0; i < l; i++) {
item = this[i];
for (w = 0, lw = whereConditions.length; w < lw; w++) {
assert = fc(item, realConditionsArr[w]);
if (assert) {
break;
}
}
if (assert) {
if (justFirst) {
return (justIndexes) ? i : item;
}
result.push((justIndexes) ? i : item);
}
}
} else {
while (l--) {
item = this[l];
for (w = 0, lw = whereConditions.length; w < lw; w++) {
assert = fc(item, realConditionsArr[w]);
if (assert) {
if (justFirst) {
return (justIndexes) ? l : item;
}
result.push((justIndexes) ? l : item);
break;
}
}
}
}
if (justFirst) {
//Because in the loops, any positive evaluation makes a return.
//At this point there was no matches.
return undefined;
}
return result;
},
// The following function is a copy of the of the value_equals utiliy of
// the toubkal project.
// https://github.com/detky/toubkal/blob/master/lib/util/value_equals.js
equals: function (a, b, enforce_properties_order, cyclic) {
/* -----------------------------------------------------------------------------------------
equals( a, b [, enforce_properties_order, cyclic] )
Returns true if a and b are deeply equal, false otherwise.
Parameters:
- a (Any type): value to compare to b
- b (Any type): value compared to a
Optional Parameters:
- enforce_properties_order (Boolean): true to check if Object properties are provided
in the same order between a and b
- cyclic (Boolean): true to check for cycles in cyclic objects
Implementation:
'a' is considered equal to 'b' if all scalar values in a and b are strictly equal as
compared with operator '===' except for these two special cases:
- 0 === -0 but are not equal.
- NaN is not === to itself but is equal.
RegExp objects are considered equal if they have the same lastIndex, i.e. both regular
expressions have matched the same number of times.
Functions must be identical, so that they have the same closure context.
"undefined" is a valid value, including in Objects
106 automated tests.
Provide options for slower, less-common use cases:
- Unless enforce_properties_order is true, if 'a' and 'b' are non-Array Objects, the
order of occurence of their attributes is considered irrelevant:
{ a: 1, b: 2 } is considered equal to { b: 2, a: 1 }
- Unless cyclic is true, Cyclic objects will throw:
RangeError: Maximum call stack size exceeded
*/
return a === b /* strick equality should be enough unless zero*/ // jshint ignore:line
&& a !== 0 /* because 0 === -0, requires test by _equals()*/ // jshint ignore:line
|| _equals(a, b) /* handles not strictly equal or zero values*/ // jshint ignore:line
;
function _equals(a, b) {
// a and b have already failed test for strict equality or are zero
var s, l, p, x, y;
// They should have the same toString() signature
if ((s = toString.call(a)) !== toString.call(b)) return false; // jshint ignore:line
switch (s) {
default: // Boolean, Date, String
return a.valueOf() === b.valueOf();
case '[object Number]':
// Converts Number instances into primitive values
// This is required also for NaN test bellow
a = +a;
b = +b;
return a ? // a is Non-zero and Non-NaN
a === b
: // a is 0, -0 or NaN
a === a ? // a is 0 or -O
1 / a === 1 / b // 1/0 !== 1/-0 because Infinity !== -Infinity
: b !== b // NaN, the only Number not equal to itself!
;
// [object Number]
case '[object RegExp]':
return a.source == b.source // jshint ignore:line
&& a.global == b.global // jshint ignore:line
&& a.ignoreCase == b.ignoreCase // jshint ignore:line
&& a.multiline == b.multiline // jshint ignore:line
&& a.lastIndex == b.lastIndex // jshint ignore:line
;
// [object RegExp]
case '[object Function]':
return false; // functions should be strictly equal because of closure context
// [object Function]
case '[object Array]':
// intentionally duplicated bellow for [object Object]
if (cyclic && (x = reference_equals(a, b)) !== null) return x; // jshint ignore:line
if ((l = a.length) != b.length) return false; // jshint ignore:line
// Both have as many elements
while (l--) {
if ((x = a[l]) === (y = b[l]) && x !== 0 || _equals(x, y)) continue; // jshint ignore:line
return false;
}
return true;
// [object Array]
case '[object Object]':
// intentionally duplicated from above for [object Array]
if (cyclic && (x = reference_equals(a, b)) !== null) return x; // jshint ignore:line
l = 0; // counter of own properties
if (enforce_properties_order) {
var properties = [];
for (p in a) {
if (a.hasOwnProperty(p)) {
properties.push(p);
if ((x = a[p]) === (y = b[p]) && x !== 0 || _equals(x, y)) continue; // jshint ignore:line
return false;
}
}
// Check if 'b' has as the same properties as 'a' in the same order
for (p in b)
if (b.hasOwnProperty(p) && properties[l++] != p) // jshint ignore:line
return false; // jshint ignore:line
} else {
for (p in a) {
if (a.hasOwnProperty(p)) {
++l;
if ((x = a[p]) === (y = b[p]) && x !== 0 || _equals(x, y)) continue; // jshint ignore:line
return false;
}
}
// Check if 'b' has as not more own properties than 'a'
for (p in b)
if (b.hasOwnProperty(p) && --l < 0) // jshint ignore:line
return false; // jshint ignore:line
}
return true;
// [object Object]
} // switch toString.call( a )
} // _equals()
/* -----------------------------------------------------------------------------------------
reference_equals( a, b )
Helper function to compare object references on cyclic objects or arrays.
Returns:
- null if a or b is not part of a cycle, adding them to object_references array
- true: same cycle found for a and b
- false: different cycle found for a and b
On the first call of a specific invocation of equal(), replaces self with inner function
holding object_references array object in closure context.
This allows to create a context only if and when an invocation of equal() compares
objects or arrays.
*/
function reference_equals(a, b) {
var object_references = [];
return (reference_equals = _reference_equals)(a, b); // jshint ignore:line
function _reference_equals(a, b) {
var l = object_references.length;
while (l--)
if (object_references[l--] === b) // jshint ignore:line
return object_references[l] === a; // jshint ignore:line
object_references.push(a, b);
return null;
} // _reference_equals()
} // reference_equals()
} // equals()
};
mainContainer.pa.Equals = mainContainer.pa.paWhereHelper.equals;
mainContainer.pa.auxiliaryFunctions = {
Contains: function (value, enforcePropsOrder, cyclic) {
var result = function (val) {
if (!val.paIsArray) {
throw new Error("PowerArray error => parameter val passed to Contains function should be an array.");
}
var l = val.length, isIndexable = false;
var typeToEvaluate = typeof value;
switch (typeToEvaluate) {
case "number":
case "string":
case "boolean":
isIndexable = true;
break;
default: //anything else
//duck type to exclude dates
if (typeof value.getMonth === 'function') {
isIndexable = true;
break;
}
isIndexable = false;
break;
}
if (isIndexable) {
return val.indexOf(value) > -1;
}
while (l--) {
if (pa.paWhereHelper.equals(val[l], value, enforcePropsOrder, cyclic)) {
return true;
}
}
return false;
};
result.paParams = arguments;
result.paParams.name = "Contains";
return result;
},
Between: function (from, to, excludeExactMatches) {
var result;
if (to < from) {
console.warn("PowerArray warn => Parameters 'from' and 'to' passed to function Between() makes no sense: Parameter 'to' (" + to + ") should be greater than from (" + from + ")");
}
if (!excludeExactMatches) {
result = function (val) {
return val >= from && val <= to;
};
} else {
result = function (val) {
return val > from && val < to;
};
}
result.paParams = arguments;
result.paParams.name = "Between";
return result;
},
EndsWith: function (value) {
var value2 = value + '';
var result = function (endsWithString) {
endsWithString = endsWithString + '';
return endsWithString.substr(endsWithString.length - (value2).length) === value2;
};
result.paParams = arguments;
result.paParams.name = "EndsWith";
return result;
},
NotEndsWith: function (value) {
var value2 = value + '';
var result = function (endsWithString) {
endsWithString = endsWithString + '';
return !(endsWithString.substr(endsWithString.length - (value2).length) === value2);
};
result.paParams = arguments;
result.paParams.name = "NotEndsWith";
return result;
},
StartsWith: function (value) {
var value2 = value + '';
var result = function (val) {
val = val + '';
return val.indexOf(value2) === 0;
};
result.paParams = arguments;
result.paParams.name = "StartsWith";
return result;
},
GreaterOrEqualThan: function (value) {
var result = function (val) {
return val >= value;
};
result.paParams = arguments;
result.paParams.name = "GreaterOrEqualThan";
return result;
},
GreaterThan: function (value) {
var result = function (val) {
return val > value;
};
result.paParams = arguments;
result.paParams.name = "GreaterThan";
return result;
},
SmallerOrEqualThan: function (value) {
var result = function (val) {
return val <= value;
};
result.paParams = arguments;
result.paParams.name = "SmallerOrEqualThan";
return result;
},
SmallerThan: function (value) {
var result = function (val) {
return val < value;
};
result.paParams = arguments;
result.paParams.name = "SmallerThan";
return result;
},
EqualTo3: function (value) {
var result = function (val) {
return val === value;
};
result.paParams = arguments;
result.paParams.name = "EqualTo3";
return result;
},
NotEqualTo3: function (value) {
var result = function (val) {
return val !== value;
};
result.paParams = arguments;
result.paParams.name = "NotEqualTo3";
return result;
},
EqualTo2: function (value) {
var result = function (val) {
// ReSharper disable once CoercedEqualsUsing
return val == value; // jshint ignore:line
};
result.paParams = arguments;
result.paParams.name = "EqualTo2";
return result;
},
NotEqualTo2: function (value) {
var result = function (val) {
// ReSharper disable once CoercedEqualsUsing
return val != value; // jshint ignore:line
};
result.paParams = arguments;
result.paParams.name = "NotEqualTo2";
return result;
},
IsUndefined: function () {
var result = function (val) {
return val === undefined;
};
result.paParams = arguments;
result.paParams.name = "IsUndefined";
return result;
},
IsDefined: function () {
var result = function (val) {
return val !== undefined;
};
result.paParams = arguments;
result.paParams.name = "IsDefined";
return result;
},
IsEmptyOrUndefined: function (val) {
if (val === undefined) {
return true;
}
if (val.paIsArray && val.length === 0) {
return true
}
if ((val + '') === '')
return true;
return false;
},
In: function (list) {
if (arguments.length > 1) {
list = Array.prototype.slice.call(arguments);
}
var result = function (val) {
return list.indexOf(val) !== -1; // jshint ignore:line
};
result.paParams = arguments;
result.paParams.name = "In";
return result;
},
NotIn: function (list) {
if (arguments.length > 1) {
list = Array.prototype.slice.call(arguments);
}
var result = function (val) {
return list.indexOf(val) === -1; // jshint ignore:line
};
result.paParams = arguments;
result.paParams.name = "NotIn";
return result;
},
EqualTo: function (object, func, enforcePropsOrder, cyclic) {
var result = function (val) {
if (func) {
return func(val, object);
} else {
return pa.paWhereHelper.equals(object, val, enforcePropsOrder, cyclic);
}
};
result.paParams = arguments;
result.paParams.name = "EqualTo";
return result;
},
Like: function (value) {
if (!value.paIsArray) {
value = Array.prototype.slice.call(arguments);
}
var result = function (val) {
var l = value.length;
while (l--) {
if (val.indexOf(value[l]) === -1) {
return false;
}
}
return true;
};
result.paParams = arguments;
result.paParams.name = "Like";
return result;
},
NotLike: function (value) {
if (!value.paIsArray) {
value = Array.prototype.slice.call(arguments);
}
var result = function (val) {
var l = value.length;
while (l--) {
if (val.indexOf(value[l]) > -1) {
return false;
}
}
return true;
};
result.paParams = arguments;
result.paParams.name = "NotLike";
return result;
},
LikeIgnoreCase: function (value) {
if (value === undefined)
throw new Error("PowerArray Error => undefined was passed to LikeIgnoreCase");
var valueCaseInsensitive = '';
if (!value.paIsArray) {
value = Array.prototype.slice.call(arguments);
}
var result = function (val) {
if (val === null || val === undefined)
return false;
var l = value.length;
while (l--) {
valueCaseInsensitive = value[l].toUpperCase();
if ((val + '').toUpperCase().indexOf(valueCaseInsensitive) === -1) {
return false;
}
}
return true;
};
result.paParams = arguments;
result.paParams.name = "LikeIgnoreCase";
return result;
},
NotLikeIgnoreCase: function (value) {
var valueCaseInsensitive = '';
if (!value.paIsArray) {
value = Array.prototype.slice.call(arguments);
}
var result = function (val) {
var l = value.length;