-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharray.js
More file actions
756 lines (690 loc) · 21.1 KB
/
Copy patharray.js
File metadata and controls
756 lines (690 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/**
* # ARRAY
* Copyright(c) 2016 Stefano Balietti
* MIT Licensed
*
* Collection of static functions to manipulate arrays
*/
(function(JSUS) {
"use strict";
function ARRAY() {}
/**
* ## ARRAY.filter
*
* Add the filter method to ARRAY objects in case the method is not
* supported natively.
*
* @see https://developer.mozilla.org/en/JavaScript/Reference/
* Global_Objects/ARRAY/filter
*/
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp */) {
if (this === void 0 || this === null) throw new TypeError();
var t = new Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function") throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
/**
* ## ARRAY.isArray
*
* Returns TRUE if a variable is an Array
*
* This method is exactly the same as `Array.isArray`,
* but it works on a larger share of browsers.
*
* @param {object} o The variable to check.
*
* @see Array.isArray
*/
ARRAY.isArray = (function(f) {
if ('function' === typeof f) return f;
else return function(o) {
if (!o) return false;
return Object.prototype.toString.call(o) === '[object Array]';
};
})(Array.isArray);
/**
* ## ARRAY.seq
*
* Returns an array of sequential numbers from start to end
*
* If start > end the series goes backward.
*
* The distance between two subsequent numbers can be controlled
* by the increment parameter.
*
* When increment is not a divider of Abs(start - end), end will
* be missing from the series.
*
* A callback function to apply to each element of the sequence
* can be passed as fourth parameter.
*
* Returns FALSE, in case parameters are incorrectly specified
*
* @param {number} start The first element of the sequence
* @param {number} end The last element of the sequence
* @param {number} increment Optional. The increment between two
* subsequents element of the sequence
* @param {Function} func Optional. A callback function that can modify
* each number of the sequence before returning it
*
* @return {array} The final sequence
*/
ARRAY.seq = function(start, end, increment, func) {
var i, out;
if ('number' !== typeof start) return false;
if (start === Infinity) return false;
if ('number' !== typeof end) return false;
if (end === Infinity) return false;
if (start === end) return [start];
if (increment === 0) return false;
if (!JSUS.inArray(typeof increment, ['undefined', 'number'])) {
return false;
}
increment = increment || 1;
func = func || function(e) {return e;};
i = start;
out = [];
if (start < end) {
while (i <= end) {
out.push(func(i));
i = i + increment;
}
}
else {
while (i >= end) {
out.push(func(i));
i = i - increment;
}
}
return out;
};
/**
* ## ARRAY.each
*
* Executes a callback on each element of the array
*
* If an error occurs returns FALSE.
*
* @param {array} array The array to loop in
* @param {Function} func The callback for each element in the array
* @param {object} context Optional. The context of execution of the
* callback. Defaults ARRAY.each
*
* @return {boolean} TRUE, if execution was successful
*/
ARRAY.each = function(array, func, context) {
if ('object' !== typeof array) return false;
if (!func) return false;
context = context || this;
var i, len = array.length;
for (i = 0 ; i < len; i++) {
func.call(context, array[i]);
}
return true;
};
/**
* ## ARRAY.map
*
* Executes a callback to each element of the array and returns the result
*
* Any number of additional parameters can be passed after the
* callback function.
*
* @return {array} The result of the mapping execution
*
* @see ARRAY.each
*/
ARRAY.map = function() {
var i, len, args, out, o;
var array, func;
array = arguments[0];
func = arguments[1];
if (!ARRAY.isArray(array)) {
JSUS.log('ARRAY.map: first parameter must be array. Found: ' +
array);
return;
}
if ('function' !== typeof func) {
JSUS.log('ARRAY.map: second parameter must be function. Found: ' +
func);
return;
}
len = arguments.length;
if (len === 3) args = [null, arguments[2]];
else if (len === 4) args = [null, arguments[2], arguments[3]];
else {
len = len - 1;
args = new Array(len);
for (i = 1; i < (len); i++) {
args[i] = arguments[i+1];
}
}
out = [], len = array.length;
for (i = 0; i < len; i++) {
args[0] = array[i];
o = func.apply(this, args);
if ('undefined' !== typeof o) out.push(o);
}
return out;
};
/**
* ## ARRAY.removeElement
*
* Removes an element from the the array, and returns it
*
* For objects, deep equality comparison is performed
* through JSUS.equals.
*
* If no element is removed returns FALSE.
*
* @param {mixed} needle The element to search in the array
* @param {array} haystack The array to search in
*
* @return {mixed} The element that was removed, FALSE if none was removed
*
* @see JSUS.equals
*/
ARRAY.removeElement = function(needle, haystack) {
var func, i;
if ('undefined' === typeof needle || !haystack) return false;
if ('object' === typeof needle) {
func = JSUS.equals;
}
else {
func = function(a, b) {
return (a === b);
};
}
for (i = 0; i < haystack.length; i++) {
if (func(needle, haystack[i])){
return haystack.splice(i,1);
}
}
return false;
};
/**
* ## ARRAY.inArray
*
* Returns TRUE if the element is contained in the array,
* FALSE otherwise
*
* For objects, deep equality comparison is performed
* through JSUS.equals.
*
* @param {mixed} needle The element to search in the array
* @param {array} haystack The array to search in
*
* @return {boolean} TRUE, if the element is contained in the array
*
* @see JSUS.equals
*/
ARRAY.inArray = function(needle, haystack) {
var func, i, len;
if (!haystack) return false;
func = JSUS.equals;
len = haystack.length;
for (i = 0; i < len; i++) {
if (func.call(this, needle, haystack[i])) {
return true;
}
}
return false;
};
ARRAY.in_array = function(needle, haystack) {
console.log('***ARRAY.in_array is deprecated. ' +
'Use ARRAY.inArray instead.***');
return ARRAY.inArray(needle, haystack);
};
/**
* ## ARRAY.getNGroups
*
* Returns an array of N array containing the same number of elements
* If the length of the array and the desired number of elements per group
* are not multiple, the last group could have less elements
*
* The original array is not modified.
*
* @see ARRAY.getGroupsSizeN
* @see ARRAY.generateCombinations
* @see ARRAY.matchN
*
* @param {array} array The array to split in subgroups
* @param {number} N The number of subgroups
*
* @return {array} Array containing N groups
*/
ARRAY.getNGroups = function(array, N) {
return ARRAY.getGroupsSizeN(array, Math.floor(array.length / N));
};
/**
* ## ARRAY.getGroupsSizeN
*
* Returns an array of arrays containing N elements each
*
* The last group could have less elements
*
* @param {array} array The array to split in subgroups
* @param {number} N The number of elements in each subgroup
*
* @return {array} Array containing groups of size N
*
* @see ARRAY.getNGroups
* @see ARRAY.generateCombinations
* @see ARRAY.matchN
*/
ARRAY.getGroupsSizeN = function(array, N) {
var copy = array.slice(0);
var len = copy.length;
var originalLen = copy.length;
var result = [];
// Init values for the loop algorithm.
var i, idx;
var group = [], count = 0;
for (i=0; i < originalLen; i++) {
// Get a random idx between 0 and array length.
idx = Math.floor(Math.random()*len);
// Prepare the array container for the elements of a new group.
if (count >= N) {
result.push(group);
count = 0;
group = [];
}
// Insert element in the group.
group.push(copy[idx]);
// Update.
copy.splice(idx,1);
len = copy.length;
count++;
}
// Add any remaining element.
if (group.length > 0) {
result.push(group);
}
return result;
};
/**
* ## ARRAY._latinSquare
*
* Generate a random Latin Square of size S
*
* If N is defined, it returns "Latin Rectangle" (SxN)
*
* A parameter controls for self-match, i.e. whether the symbol "i"
* is found or not in in column "i".
*
* @api private
* @param {number} S The number of rows
* @param {number} Optional. N The number of columns. Defaults N = S
* @param {boolean} Optional. If TRUE self-match is allowed. Defaults TRUE
*
* @return {array} The resulting latin square (or rectangle)
*/
ARRAY._latinSquare = function(S, N, self) {
self = ('undefined' === typeof self) ? true : self;
// Infinite loop.
if (S === N && !self) return false;
var seq = [];
var latin = [];
for (var i=0; i< S; i++) {
seq[i] = i;
}
var idx = null;
var start = 0;
var limit = S;
var extracted = [];
if (!self) {
limit = S-1;
}
for (i=0; i < N; i++) {
do {
idx = JSUS.randomInt(start,limit);
}
while (JSUS.inArray(idx, extracted));
extracted.push(idx);
if (idx == 1) {
latin[i] = seq.slice(idx);
latin[i].push(0);
}
else {
latin[i] = seq.slice(idx).concat(seq.slice(0,(idx)));
}
}
return latin;
};
/**
* ## ARRAY.latinSquare
*
* Generate a random Latin Square of size S
*
* If N is defined, it returns "Latin Rectangle" (SxN)
*
* @param {number} S The number of rows
* @param {number} Optional. N The number of columns. Defaults N = S
*
* @return {array} The resulting latin square (or rectangle)
*/
ARRAY.latinSquare = function(S, N) {
if (!N) N = S;
if (!S || S < 0 || (N < 0)) return false;
if (N > S) N = S;
return ARRAY._latinSquare(S, N, true);
};
/**
* ## ARRAY.latinSquareNoSelf
*
* Generate a random Latin Square of size Sx(S-1), where
* in each column "i", the symbol "i" is not found
*
* If N < S, it returns a "Latin Rectangle" (SxN)
*
* @param {number} S The number of rows
* @param {number} Optional. N The number of columns. Defaults N = S-1
*
* @return {array} The resulting latin square (or rectangle)
*/
ARRAY.latinSquareNoSelf = function(S, N) {
if (!N) N = S-1;
if (!S || S < 0 || (N < 0)) return false;
if (N > S) N = S-1;
return ARRAY._latinSquare(S, N, false);
};
/**
* ## ARRAY.generateCombinations
*
* Generates all distinct combinations of exactly r elements each
*
* @param {array} array The array from which the combinations are extracted
* @param {number} r The number of elements in each combination
*
* @return {array} The total sets of combinations
*
* @see ARRAY.getGroupSizeN
* @see ARRAY.getNGroups
* @see ARRAY.matchN
*
* Kudos: http://rosettacode.org/wiki/Combinations#JavaScript
*/
ARRAY.generateCombinations = function combinations(arr, k) {
var i, subI, ret, sub, next;
ret = [];
for (i = 0; i < arr.length; i++) {
if (k === 1) {
ret.push( [ arr[i] ] );
}
else {
sub = combinations(arr.slice(i+1, arr.length), k-1);
for (subI = 0; subI < sub.length; subI++ ){
next = sub[subI];
next.unshift(arr[i]);
ret.push( next );
}
}
}
return ret;
};
/**
* ## ARRAY.matchN
*
* Match each element of the array with N random others
*
* If strict is equal to true, elements cannot be matched multiple times.
*
* *Important*: this method has a bug / feature. If the strict parameter
* is set, the last elements could remain without match, because all the
* other have been already used. Another recombination would be able
* to match all the elements instead.
*
* @param {array} array The array in which operate the matching
* @param {number} N The number of matches per element
* @param {boolean} strict Optional. If TRUE, matched elements cannot be
* repeated. Defaults, FALSE
*
* @return {array} The results of the matching
*
* @see ARRAY.getGroupSizeN
* @see ARRAY.getNGroups
* @see ARRAY.generateCombinations
*/
ARRAY.matchN = function(array, N, strict) {
var result, i, copy, group, len, found;
if (!array) return;
if (!N) return array;
result = [];
len = array.length;
found = [];
for (i = 0 ; i < len ; i++) {
// Recreate the array.
copy = array.slice(0);
copy.splice(i,1);
if (strict) {
copy = ARRAY.arrayDiff(copy,found);
}
group = ARRAY.getNRandom(copy,N);
// Add to the set of used elements.
found = found.concat(group);
// Re-add the current element.
group.splice(0,0,array[i]);
result.push(group);
// Update.
group = [];
}
return result;
};
/**
* ## ARRAY.rep
*
* Appends an array to itself a number of times and return a new array
*
* The original array is not modified.
*
* @param {array} array the array to repeat
* @param {number} times The number of times the array must be appended
* to itself
*
* @return {array} A copy of the original array appended to itself
*/
ARRAY.rep = function(array, times) {
var i, result;
if (!array) return;
if (!times) return array.slice(0);
if (times < 1) {
JSUS.log('times must be greater or equal 1', 'ERR');
return;
}
i = 1;
result = array.slice(0);
for (; i < times; i++) {
result = result.concat(array);
}
return result;
};
/**
* ## ARRAY.stretch
*
* Repeats each element of the array N times
*
* N can be specified as an integer or as an array. In the former case all
* the elements are repeat the same number of times. In the latter, each
* element can be repeated a custom number of times. If the length of the
* `times` array differs from that of the array to stretch a recycle rule
* is applied.
*
* The original array is not modified.
*
* E.g.:
*
* ```js
* var foo = [1,2,3];
*
* ARRAY.stretch(foo, 2); // [1, 1, 2, 2, 3, 3]
*
* ARRAY.stretch(foo, [1,2,3]); // [1, 2, 2, 3, 3, 3];
*
* ARRAY.stretch(foo, [2,1]); // [1, 1, 2, 3, 3];
* ```
*
* @param {array} array the array to strech
* @param {number|array} times The number of times each element
* must be repeated
* @return {array} A stretched copy of the original array
*/
ARRAY.stretch = function(array, times) {
var result, i, repeat, j;
if (!array) return;
if (!times) return array.slice(0);
if ('number' === typeof times) {
if (times < 1) {
JSUS.log('times must be greater or equal 1', 'ERR');
return;
}
times = ARRAY.rep([times], array.length);
}
result = [];
for (i = 0; i < array.length; i++) {
repeat = times[(i % times.length)];
for (j = 0; j < repeat ; j++) {
result.push(array[i]);
}
}
return result;
};
/**
* ## ARRAY.arrayIntersect
*
* Computes the intersection between two arrays
*
* Arrays can contain both primitive types and objects.
*
* @param {array} a1 The first array
* @param {array} a2 The second array
* @return {array} All the values of the first array that are found
* also in the second one
*/
ARRAY.arrayIntersect = function(a1, a2) {
return a1.filter( function(i) {
return JSUS.inArray(i, a2);
});
};
/**
* ## ARRAY.arrayDiff
*
* Performs a diff between two arrays
*
* Arrays can contain both primitive types and objects.
*
* @param {array} a1 The first array
* @param {array} a2 The second array
* @return {array} All the values of the first array that are not
* found in the second one
*/
ARRAY.arrayDiff = function(a1, a2) {
return a1.filter( function(i) {
return !(JSUS.inArray(i, a2));
});
};
/**
* ## ARRAY.shuffle
*
* Shuffles the elements of the array using the Fischer algorithm
*
* The original array is not modified, and a copy is returned.
*
* @param {array} shuffle The array to shuffle
*
* @return {array} copy The shuffled array
*
* @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
ARRAY.shuffle = function(array) {
var copy, len, j, tmp, i;
if (!array) return;
copy = Array.prototype.slice.call(array);
len = array.length-1; // ! -1
for (i = len; i > 0; i--) {
j = Math.floor(Math.random()*(i+1));
tmp = copy[j];
copy[j] = copy[i];
copy[i] = tmp;
}
return copy;
};
/**
* ## ARRAY.getNRandom
*
* Select N random elements from the array and returns them
*
* @param {array} array The array from which extracts random elements
* @paran {number} N The number of random elements to extract
*
* @return {array} An new array with N elements randomly chosen
*/
ARRAY.getNRandom = function(array, N) {
return ARRAY.shuffle(array).slice(0,N);
};
/**
* ## ARRAY.distinct
*
* Removes all duplicates entries from an array and returns a copy of it
*
* Does not modify original array.
*
* Comparison is done with `JSUS.equals`.
*
* @param {array} array The array from which eliminates duplicates
*
* @return {array} A copy of the array without duplicates
*
* @see JSUS.equals
*/
ARRAY.distinct = function(array) {
var out = [];
if (!array) return out;
ARRAY.each(array, function(e) {
if (!ARRAY.inArray(e, out)) {
out.push(e);
}
});
return out;
};
/**
* ## ARRAY.transpose
*
* Transposes a given 2D array.
*
* The original array is not modified, and a new copy is
* returned.
*
* @param {array} array The array to transpose
*
* @return {array} The Transposed Array
*/
ARRAY.transpose = function(array) {
if (!array) return;
// Calculate width and height
var w, h, i, j, t = [];
w = array.length || 0;
h = (ARRAY.isArray(array[0])) ? array[0].length : 0;
if (w === 0 || h === 0) return t;
for ( i = 0; i < h; i++) {
t[i] = [];
for ( j = 0; j < w; j++) {
t[i][j] = array[j][i];
}
}
return t;
};
JSUS.extend(ARRAY);
})('undefined' !== typeof JSUS ? JSUS : module.parent.exports.JSUS);