/
CrioArray.js
850 lines (758 loc) · 18.9 KB
/
CrioArray.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
// external dependencies
import stringify from 'json-stringify-safe';
import hashIt from 'hash-it';
import {parse} from 'pathington';
import {
get,
has,
merge,
remove,
set
} from 'unchanged';
// classes
import CrioObject from './CrioObject';
// constants
import {
ARRAY_FALLBACK_PROTOTYPE_METHODS,
ARRAY_UNSCOPABLES
} from './constants';
// is
import {
isArray,
isCrio,
isEqual,
isUndefined
} from './is';
// utils
import {
createIterator,
find,
getCrioedObject,
getEntries,
getRelativeValue,
getValues,
thaw
} from './utils';
let hasAppliedPrototype = false;
class CrioArray extends Array {
constructor(array) {
super(isArray(array) ? array.length : array || 0);
if (!hasAppliedPrototype) {
applyPrototype(); // eslint-disable-line no-use-before-define
hasAppliedPrototype = true;
}
return isCrio(array)
? array.toArray()
: isArray(array)
? array.reduce((crioArray, item, index) => {
crioArray[index] = getCrioedObject(item);
return crioArray;
}, this)
: this;
}
get hashCode() {
return hashIt(this, true);
}
/**
* @function clear
* @memberof CrioArray
*folder
* @description
* get a new empty array
*
* @returns {CrioArray} the empty array
*/
clear() {
return new CrioArray();
}
/**
* @function compact
* @memberof CrioArray
*
* @description
* get a new array with values from the original array that are truthy
*
* @returns {CrioArray} the array with only truthy values
*/
compact() {
return this.filter((item) => !!item);
}
/**
* @function copyWithin
*
* @description
* move values around within the array
*
* @param {number} targetIndex target to copy
* @param {number} [startIndex=0] index to start copying to
* @param {number} [endIndex=this.length] index to stop copying to
* @returns {CrioArray} array with target copied in appropriate spots
*/
copyWithin(targetIndex, startIndex = 0, endIndex = this.length) {
const clone = [...this];
const length = this.length >>> 0;
const final = getRelativeValue(endIndex >> 0, length);
let to = getRelativeValue(targetIndex >> 0, length),
from = getRelativeValue(startIndex >> 0, length),
count = Math.min(final - from, length - to),
direction = 1;
if (from < to && to < from + count) {
direction = -1;
from += count - 1;
to += count - 1;
}
while (count > 0) {
if (from in clone) {
clone[to] = clone[from];
} else {
delete clone[to];
}
from += direction;
to += direction;
count--;
}
return new this.constructor(clone);
}
/**
* @function delete
* @memberof CrioArray
*
* @description
* delete the value in the array at key, either shallow or deep
*
* @param {Array<number|string>|number} key the key to delete
* @returns {CrioArray} the array with the key deleted
*/
delete(key) {
return remove(key, this);
}
/**
* @function difference
* @memberof CrioArray
*
* @description
* find the values in this that do not exist in any of the arrays passed
*
* @param {...Array<Array<*>>} arrays arrays to get the difference of
* @returns {CrioArray} array of items matching diffference criteria
*/
difference(...arrays) {
if (!arrays.length) {
return this;
}
let indexOfItem;
return arrays.reduce((differenceArray, array) => {
if (isArray(array)) {
array.forEach((item) => {
indexOfItem = differenceArray.indexOf(item);
if (~indexOfItem) {
differenceArray = differenceArray.splice(indexOfItem, 1);
}
});
}
return differenceArray;
}, this);
}
/**
* @function entries
* @memberof CrioArray
*
* @description
* get the pairs of [key, value] in the crio
*
* @returns {CrioArray} [key, value] pairs
*/
entries() {
return getEntries(this);
}
/**
* @function equals
* @memberof CrioArray
*
* @description
* does the object passed equal the crio
*
* @param {*} object object to compare against the instance
* @returns {boolean} is the object equivalent in value
*/
equals(object) {
return isEqual(this, object);
}
/**
* @function fill
*
* @description
* fill the array at certain indices with the value passed
*
* @param {*} value the value to fill the indices with
* @param {number} [startIndex=0] the starting index to fill
* @param {number} [endIndex=this.length] the ending index to fill
* @returns {CrioArray} array with values filled appropriately
*/
fill(value, startIndex = 0, endIndex = this.length) {
const from = startIndex < 0 ? this.length + startIndex : startIndex;
const to = endIndex < 0 ? this.length + endIndex : endIndex;
const crioedValue = getCrioedObject(value);
return this.map((item, index) => (index >= from && index < to ? crioedValue : item));
}
/**
* @function findLast
* @memberof CrioArray
*
* @description
* find an item in the crio if it exists, starting from the end and iteratng to the start
*
* @param {function} fn function to test for finding the item
* @returns {*} found item or undefined
*/
findLast(fn) {
return find(this, fn, false, true);
}
/**
* @function findLastIndex
* @memberof CrioArray
*
* @description
* find the matching index based on truthy return from fn starting from end
*
* @param {function} fn function to use for test in iteration
* @returns {number} index of match, or -1
*/
findLastIndex(fn) {
return find(this, fn, true, true);
}
/**
* @function first
* @memberof CrioArray
*
* @description
* take the first n number of items in the array
*
* @param {number} [size=1] size of elements to take from beginning of array
* @returns {CrioArray}
*/
first(size = 1) {
return this.slice(0, size);
}
/**
* @function forEach
* @memberof CrioArray
*
* @description
* iterate over the array executing fn
*
* @param {function} fn the function to execute
* @returns {CrioArray} the original array
*/
forEach(fn) {
Array.prototype.forEach.call(this, fn);
return this;
}
/**
* @function get
* @memberof CrioArray
*
* @description
* get the item at key passed, either shallow or deeply nested
*
* @param {Array<number|string>|number} key key to retrieve
* @returns {*} item found at key
*/
get(key) {
return get(key, this);
}
/**
* @function has
* @memberof CrioArray
*
* @description
* does the crio have the key passed, either shallow or deeply nested
*
* @param {Array<number|string>|number} key key to test
* @returns {boolean} does the crio have the key
*/
has(key) {
return has(key, this);
}
/**
* @function intersection
* @memberof CrioArray
*
* @description
* find the values in that exist in this and each of the arrays passed
*
* @param {...Array<Array>} arrays to find the intersecting values of
* @returns {CrioArray} array of values that exist in all arrays
*/
intersection(...arrays) {
if (!arrays.length) {
return this;
}
let indices = [],
indexOfItem;
const reducedArrays = [this, ...arrays].reduce((items, array) => {
if (isArray(array)) {
array.forEach((item) => {
indexOfItem = items.indexOf(item);
if (~indexOfItem) {
return indices[indexOfItem]++;
}
indices[items.length] = 1;
items.push(item);
});
}
return items;
}, []);
const newLength = arrays.length + 1;
return new CrioArray(reducedArrays.filter((itemIgnored, index) => indices[index] === newLength));
}
/**
* @function isArray
* @memberof CrioArray
*
* @description
* is the crio an array
*
* @returns {boolean} is the crio an array
*/
isArray() {
return true;
}
/**
* @function isObject
* @memberof CrioArray
*
* @description
* is the crio an object
*
* @returns {boolean} is the crio an object
*/
isObject() {
return false;
}
/**
* @function join
* @memberof CrioArray
*
* @description
* join the values in the crio as a string, combined with separator
*
* @param {string} [separator] character(s) to place between strings in combination
* @returns {string} parameters joined by separator in string
*/
join(separator) {
return this.thaw().join(separator);
}
/**
* @function keys
* @memberof CrioArray
*
* @description
* get the keys of the crio
*
* @returns {CrioArray<number>} keys in the crio
*/
keys() {
return new CrioArray(Object.keys(this).map(Number));
}
/**
* @function last
* @memberof CrioArray
*
* @description
* take the last n number of items in the array
*
* @param {number} [size=1] size of elements to take from end of array
* @returns {CrioArray}
*/
last(size = 1) {
return this.slice(this.length - size);
}
/**
* @function map
* @memberof CrioArray
*
* @description
* map over the array returning the mapped items
*
* @param {function} fn the function to map
* @returns {CrioArray} the mapped array
*/
map(fn) {
return Array.prototype.map.call(this, (item, index) => getCrioedObject(fn(item, index, this)));
}
/**
* @function merge
* @memberof CrioArray
*
* @description
* merge arrays with the original array
*
* @param {Array<number|string>|number|null} key the key to merge into
* @param {...Array<CrioArray>} objects objects to merge with the crio
* @returns {CrioArray} merged array
*/
merge(key, ...objects) {
return objects.reduce((mergedObject, object) => merge(key, getCrioedObject(object), mergedObject), this);
}
/**
* @function mutate
* @memberof CrioArray
*
* @description
* work with the array in a mutated way and return the crioed result of that call
*
* @param {function} fn function to apply to crio
* @returns {*} crioed value resulting from the call
*/
mutate(fn) {
return getCrioedObject(fn(this.thaw(), this));
}
/**
* @function pluck
* @memberof CrioArray
*
* @description
* get the values in each object in the collection at key, either shallow or deeply nested
*
* @param {string} key key to find value of in collection object
* @returns {CrioArray} array of plucked values
*/
pluck(key) {
const parsedKey = parse(key);
const arrayToPluck = get(parsedKey.slice(0, parsedKey.length - 1), this);
const finalKey = parsedKey.slice(-1);
return arrayToPluck.map((item) => get(finalKey, item));
}
/**
* @function pop
* @memberof CrioArray
*
* @description
* get crio based on current crio with last item removed
*
* @returns {CrioArray} array with the last value removed
*/
pop() {
return this.slice(0, this.length - 1);
}
/**
* @function push
* @memberof CrioArray
*
* @description
* push one to many items to the current crio
*
* @param {...Array<*>} items the items to add to the array
* @returns {CrioArray} array with the values added
*/
push(...items) {
return items.length ? this.concat(items) : this;
}
/**
* @function reduce
* @memberof CrioObject
*
* @description
* reduce the crio down to a single value, starting with initial value
*
* @param {function} fn the function to iterate with
* @param {*} initialValue the initial value of the reduction
* @returns {*} the reduced value
*/
reduce(fn, initialValue) {
return getCrioedObject(
Array.prototype.reduce.call(this, (value, item, index) => fn(value, item, index, this), initialValue)
);
}
/**
* @function reduceRight
* @memberof CrioObject
*
* @description
* reduce the crio down to a single value, starting with initial value, starting from the end of the array
* and iterating to the start
*
* @param {function} fn the function to iterate with
* @param {*} initialValue the initial value of the reduction
* @returns {*} the reduced value
*/
reduceRight(fn, initialValue) {
return getCrioedObject(
Array.prototype.reduceRight.call(this, (value, item, index) => fn(value, item, index, this), initialValue)
);
}
/**
* @function reverse
* @memberof CrioArray
*
* @description
* get the same values, but in reverse order
*
* @returns {CrioArray} array with the items reversed in order
*/
reverse() {
return new CrioArray([...this].reverse());
}
/**
* @function set
* @memberof CrioArray
*
* @description
* set the value at the key passed
*
* @param {Array<number|string>|number} key key to assign value to
* @param {*} value value to assign
* @returns {CrioArray} array with value set at key
*/
set(key, value) {
return set(key, getCrioedObject(value), this);
}
/**
* @function shift
* @memberof CrioArray
*
* @description
* get crio based on current crio with first item removed
*
* @returns {CrioArray} array with the first item removed
*/
shift() {
return this.slice(1);
}
/**
* @function sort
* @memberof CrioArray
*
* @description
* sort the collection by the fn passed
*
* @param {function} fn the function to sort based on
* @returns {CrioArray} array with the items sorted
*/
sort(fn) {
const clone = [...this];
clone.sort(fn);
return new CrioArray(clone);
}
/**
* @function splice
* @memberof CrioArray
*
* @description
* splice the values into or out of the array
*
* @param {number} [start=0] starting index to splice
* @param {number} [deleteCount=1] length from starting index to removes
* @param {...Array<*>} items items to insert after delete is complete
* @returns {CrioArray} array with the value spliced in / out
*/
splice(...args) {
const clone = [...this];
clone.splice(...args);
return new CrioArray(clone);
}
/**
* @function thaw
* @memberof CrioArray
*
* @description
* create a plain JS version of the array
*
* @returns {Array<*>} plain JS version of the array
*/
thaw() {
return thaw(this);
}
/**
* @function toArray
* @memberof CrioArray
*
* @description
* convert the array to an array
*
* @returns {CrioArray} the array
*/
toArray() {
return this;
}
/**
* @function toLocaleString
* @memberof CrioArray
*
* @description
* convert the array to stringified form
*
* @param {function} [serializer] the serialization method to use
* @param {number} [indent] the number of spaces to indent the values
* @returns {string} stringified array
*/
toLocaleString(serializer, indent) {
return this.toString(
serializer,
indent
);
}
/**
* @function toObject
* @memberof CrioArray
*
* @description
* convert the crio to an object if it isn't already
*
* @returns {CrioObject} new object from the array
*/
toObject() {
return this.reduce((object, item, index) => {
object[index] = item;
return object;
}, new CrioObject({}));
}
/**
* @function toString
* @memberof CrioArray
*
* @description
* convert the array to stringified form
*
* @param {function} [serializer] the serialization method to use
* @param {number} [indent] the number of spaces to indent the values
* @returns {string} stringified array
*/
toString(serializer, indent) {
return stringify(this, serializer, indent);
}
/**
* @function unique
* @memberof CrioArray
*
* @description
* return the current CrioArray with the duplicate values removed
*
* @returns {CrioArray} new crio instance
*/
unique() {
let hashArray = [],
newArray = [],
hasHashCode = false,
hashCode,
storeValue;
return this.filter((item) => {
hashCode = item ? item.hashCode : undefined;
hasHashCode = !isUndefined(hashCode);
storeValue = !~newArray.indexOf(item) && (!hasHashCode || !~hashArray.indexOf(hashCode));
if (storeValue) {
newArray.push(item);
if (hasHashCode) {
hashArray.push(hashCode);
}
}
return storeValue;
});
}
/**
* @function unshift
* @memberof CrioArray
*
* @description
* add items passed to the beginning of the crio array
*
* @param {...Array<*>} items items to prepend to the array
* @returns {CrioArray} array with the items prepended
*/
unshift(...items) {
return items.length ? new CrioArray([...items, ...this]) : this;
}
/**
* @function valueOf
* @memberof CrioArray
*
* @description
* get the array value
*
* @returns {CrioArray} the array
*/
valueOf() {
return this;
}
/**
* @function values
* @memberof CrioArray
*
* @description
* get the values of the array as an array
*
* @returns {CrioArray} values in the array
*/
values() {
return getValues(this);
}
/**
* @function xor
* @memberof CrioArray
*
* @description
* find the values that are the symmetric difference of this and the arrays passed
*
* @param {Array<Array>} arrays arrays to find symmetric values in
* @returns {CrioArray} array of the symmetric differences of all the arrays
*/
xor(...arrays) {
if (!arrays.length) {
return this;
}
let indicesToRemove = [],
indexOfItem;
const reducedItems = [this, ...arrays].reduce((items, array) => {
if (isArray(array)) {
array.forEach((item) => {
indexOfItem = items.indexOf(item);
if (~indexOfItem) {
indicesToRemove.push(indexOfItem);
} else {
items = items.push(item);
}
});
}
return items;
}, new CrioArray([]));
return reducedItems.filter((itemIgnored, index) => !~indicesToRemove.indexOf(index));
}
}
export function applyPrototype() {
Object.keys(ARRAY_FALLBACK_PROTOTYPE_METHODS).forEach((key) => {
if (typeof Array.prototype[key] !== 'function') {
CrioArray.prototype[key] = function(...args) {
return ARRAY_FALLBACK_PROTOTYPE_METHODS[key](this, ...args);
};
}
});
if (typeof Symbol === 'function') {
if (Symbol.species) {
Object.defineProperty(CrioArray, Symbol.species, {
configurable: false,
enumerable: false,
get() {
return CrioArray;
},
});
}
if (Symbol.iterator) {
Object.defineProperty(CrioArray.prototype, Symbol.iterator, {
configurable: false,
enumerable: false,
value: createIterator(),
writable: false,
});
}
if (Symbol.unscopables) {
Object.defineProperty(CrioArray.prototype, Symbol.unscopables, {
configurable: false,
enumerable: false,
value: ARRAY_UNSCOPABLES,
writable: false,
});
}
}
}
export default CrioArray;