forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs-data.es2015.js
12340 lines (12318 loc) · 453 KB
/
js-data.es2015.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
/*!
* js-data
* @version 4.0.0-beta.1 - Homepage <http://www.js-data.io/>
* @author js-data project authors
* @copyright (c) 2014-2016 js-data project authors
* @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE>
*
* @overview js-data is a framework-agnostic, datastore-agnostic ORM/ODM for Node.js and the Browser.
*/
/**
* Utility methods used by JSData.
*
* @example
* import { utils } from 'js-data';
* console.log(utils.isString('foo')); // true
*
* @namespace utils
* @type {Object}
*/
const DOMAIN = 'utils';
const INFINITY = 1 / 0;
const MAX_INTEGER = 1.7976931348623157e308;
const BOOL_TAG = '[object Boolean]';
const DATE_TAG = '[object Date]';
const FUNC_TAG = '[object Function]';
const NUMBER_TAG = '[object Number]';
const OBJECT_TAG = '[object Object]';
const REGEXP_TAG = '[object RegExp]';
const STRING_TAG = '[object String]';
const objToString = Object.prototype.toString;
const PATH = /^(.+)\.(.+)$/;
const ERRORS = {
'400'(...args) {
return `expected: ${args[0]}, found: ${args[2] ? args[1] : typeof args[1]}`;
},
'404'(...args) {
return `${args[0]} not found`;
}
};
const toInteger = value => {
if (!value) {
return 0;
}
// Coerce to number
value = +value;
if (value === INFINITY || value === -INFINITY) {
const sign = value < 0 ? -1 : 1;
return sign * MAX_INTEGER;
}
const remainder = value % 1;
return value === value ? (remainder ? value - remainder : value) : 0; // eslint-disable-line
};
const toStr = value => objToString.call(value);
const isPlainObject = value => !!value && typeof value === 'object' && value.constructor === Object;
const mkdirP = (object, path) => {
if (!path) {
return object;
}
const parts = path.split('.');
parts.forEach(key => {
if (!object[key]) {
object[key] = {};
}
object = object[key];
});
return object;
};
const utils = {
/**
* Shallow copy properties that meet the following criteria from `src` to
* `dest`:
*
* - own enumerable
* - not a function
* - does not start with "_"
*
* @method utils._
* @param {object} dest Destination object.
* @param {object} src Source object.
* @private
* @since 3.0.0
*/
_(dest, src) {
utils.forOwn(src, (value, key) => {
if (key && dest[key] === undefined && !utils.isFunction(value) && key.indexOf('_') !== 0) {
dest[key] = value;
}
});
},
/**
* Recursively iterates over relations found in `opts.with`.
*
* @method utils._forRelation
* @param {object} opts Configuration options.
* @param {Relation} def Relation definition.
* @param {Function} fn Callback function.
* @param {*} [thisArg] Execution context for the callback function.
* @private
* @since 3.0.0
*/
_forRelation(opts = {}, def, fn, thisArg) {
const relationName = def.relation;
let containedName = null;
let index;
opts.with = opts.with || [];
if ((index = utils._getIndex(opts.with, relationName)) >= 0) {
containedName = relationName;
}
else if ((index = utils._getIndex(opts.with, def.localField)) >= 0) {
containedName = def.localField;
}
if (opts.withAll) {
fn.call(thisArg, def, {});
return;
}
else if (!containedName) {
return;
}
const optsCopy = {};
utils.fillIn(optsCopy, def.getRelation());
utils.fillIn(optsCopy, opts);
optsCopy.with = opts.with.slice();
optsCopy._activeWith = optsCopy.with.splice(index, 1)[0];
optsCopy.with.forEach((relation, i) => {
if (relation &&
relation.indexOf(containedName) === 0 &&
relation.length >= containedName.length &&
relation[containedName.length] === '.') {
optsCopy.with[i] = relation.substr(containedName.length + 1);
}
else {
optsCopy.with[i] = '';
}
});
fn.call(thisArg, def, optsCopy);
},
/**
* Find the index of a relation in the given list
*
* @method utils._getIndex
* @param {string[]} list List to search.
* @param {string} relation Relation to find.
* @private
* @returns {number}
*/
_getIndex(list, relation) {
let index = -1;
list.forEach((_relation, i) => {
if (_relation === relation) {
index = i;
return false;
}
else if (utils.isObject(_relation)) {
if (_relation.relation === relation) {
index = i;
return false;
}
}
});
return index;
},
/**
* Define hidden (non-enumerable), writable properties on `target` from the
* provided `props`.
*
* @example
* import { utils } from 'js-data';
* function Cat () {}
* utils.addHiddenPropsToTarget(Cat.prototype, {
* say () {
* console.log('meow');
* }
* });
* const cat = new Cat();
* cat.say(); // "meow"
*
* @method utils.addHiddenPropsToTarget
* @param {object} target That to which `props` should be added.
* @param {object} props Properties to be added to `target`.
* @since 3.0.0
*/
addHiddenPropsToTarget(target, props) {
const map = {};
Object.keys(props).forEach(propName => {
const descriptor = Object.getOwnPropertyDescriptor(props, propName);
descriptor.enumerable = false;
map[propName] = descriptor;
});
Object.defineProperties(target, map);
},
/**
* Return whether the two objects are deeply different.
*
* @example
* import { utils } from 'js-data';
* utils.areDifferent({}, {}); // false
* utils.areDifferent({ a: 1 }, { a: 1 }); // false
* utils.areDifferent({ foo: 'bar' }, {}); // true
*
* @method utils.areDifferent
* @param newObject
* @param oldObject
* @param {object} [opts] Configuration options.
* @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.
* @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.
* @returns {boolean} Whether the two objects are deeply different.
* @see utils.diffObjects
* @since 3.0.0
*/
areDifferent(newObject, oldObject, opts = {}) {
const diff = utils.diffObjects(newObject, oldObject, opts);
const diffCount = Object.keys(diff.added).length + Object.keys(diff.removed).length + Object.keys(diff.changed).length;
return diffCount > 0;
},
/**
* Deep copy a value.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' } };
* const b = utils.copy(a);
* a === b; // false
* utils.areDifferent(a, b); // false
*
* @param {*} from Value to deep copy.
* @param {*} [to] Destination object for the copy operation.
* @param {*} [stackFrom] For internal use.
* @param {*} [stackTo] For internal use.
* @param {string[]|RegExp[]} [blacklist] List of strings or RegExp of
* properties to skip.
* @param {boolean} [plain] Whether to make a plain copy (don't try to use
* original prototype).
* @returns {*} Deep copy of `from`.
* @since 3.0.0
*/
copy(from, to, stackFrom, stackTo, blacklist, plain) {
if (!to) {
to = from;
if (from) {
if (utils.isArray(from)) {
to = utils.copy(from, [], stackFrom, stackTo, blacklist, plain);
}
else if (utils.isDate(from)) {
to = new Date(from.getTime());
}
else if (utils.isRegExp(from)) {
to = new RegExp(from.source, from.toString().match(/[^/]*$/)[0]);
to.lastIndex = from.lastIndex;
}
else if (utils.isObject(from)) {
if (plain) {
to = utils.copy(from, {}, stackFrom, stackTo, blacklist, plain);
}
else {
to = utils.copy(from, Object.create(Object.getPrototypeOf(from)), stackFrom, stackTo, blacklist, plain);
}
}
}
}
else {
if (from === to) {
throw utils.err(`${DOMAIN}.copy`)(500, 'Cannot copy! Source and destination are identical.');
}
stackFrom = stackFrom || [];
stackTo = stackTo || [];
if (utils.isObject(from)) {
const index = stackFrom.indexOf(from);
if (index !== -1) {
return stackTo[index];
}
stackFrom.push(from);
stackTo.push(to);
}
let result;
if (utils.isArray(from)) {
let i;
to.length = 0;
for (i = 0; i < from.length; i++) {
result = utils.copy(from[i], null, stackFrom, stackTo, blacklist, plain);
if (utils.isObject(from[i])) {
stackFrom.push(from[i]);
stackTo.push(result);
}
to.push(result);
}
}
else {
if (utils.isArray(to)) {
to.length = 0;
}
else {
utils.forOwn(to, (value, key) => {
delete to[key];
});
}
for (const key in from) {
if (from.hasOwnProperty(key)) {
if (utils.isBlacklisted(key, blacklist)) {
continue;
}
result = utils.copy(from[key], null, stackFrom, stackTo, blacklist, plain);
if (utils.isObject(from[key])) {
stackFrom.push(from[key]);
stackTo.push(result);
}
to[key] = result;
}
}
}
}
return to;
},
/**
* Recursively shallow fill in own enumerable properties from `source` to
* `dest`.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' }, beep: 'boop' };
* const b = { beep: 'bip' };
* utils.deepFillIn(b, a);
* console.log(b); // {"foo":{"bar":"baz"},"beep":"bip"}
*
* @method utils.deepFillIn
* @param {object} dest The destination object.
* @param {object} source The source object.
* @see utils.fillIn
* @see utils.deepMixIn
* @since 3.0.0
*/
deepFillIn(dest, source) {
if (source) {
utils.forOwn(source, (value, key) => {
const existing = dest[key];
if (isPlainObject(value) && isPlainObject(existing)) {
utils.deepFillIn(existing, value);
}
else if (!dest.hasOwnProperty(key) || dest[key] === undefined) {
dest[key] = value;
}
});
}
return dest;
},
/**
* Recursively shallow copy enumerable properties from `source` to `dest`.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' }, beep: 'boop' };
* const b = { beep: 'bip' };
* utils.deepFillIn(b, a);
* console.log(b); // {"foo":{"bar":"baz"},"beep":"boop"}
*
* @method utils.deepMixIn
* @param {object} dest The destination object.
* @param {object} source The source object.
* @see utils.fillIn
* @see utils.deepFillIn
* @since 3.0.0
*/
deepMixIn(dest, source) {
if (source) {
// tslint:disable-next-line:forin
for (const key in source) {
const value = source[key];
const existing = dest[key];
if (isPlainObject(value) && isPlainObject(existing)) {
utils.deepMixIn(existing, value);
}
else {
dest[key] = value;
}
}
}
return dest;
},
/**
* Return a diff of the base object to the comparison object.
*
* @example
* import { utils } from 'js-data';
* const oldObject = { foo: 'bar', a: 1234 };
* const newObject = { beep: 'boop', a: 5678 };
* const diff = utils.diffObjects(oldObject, newObject);
* console.log(diff.added); // {"beep":"boop"}
* console.log(diff.changed); // {"a":5678}
* console.log(diff.removed); // {"foo":undefined}
*
* @method utils.diffObjects
* @param {object} newObject Comparison object.
* @param {object} oldObject Base object.
* @param {object} [opts] Configuration options.
* @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.
* @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.
* @returns {Object} The diff from the base object to the comparison object.
* @see utils.areDifferent
* @since 3.0.0
*/
diffObjects(newObject, oldObject, opts = {}) {
let equalsFn = opts.equalsFn;
const blacklist = opts.ignore;
const diff = {
added: {},
changed: {},
removed: {}
};
if (!utils.isFunction(equalsFn)) {
equalsFn = utils.deepEqual;
}
const newKeys = Object.keys(newObject).filter(key => !utils.isBlacklisted(key, blacklist));
const oldKeys = Object.keys(oldObject).filter(key => !utils.isBlacklisted(key, blacklist));
// Check for properties that were added or changed
newKeys.forEach(key => {
const oldValue = oldObject[key];
const newValue = newObject[key];
if (equalsFn(oldValue, newValue)) {
return;
}
if (oldValue === undefined) {
diff.added[key] = newValue;
}
else {
diff.changed[key] = newValue;
}
});
// Check for properties that were removed
oldKeys.forEach(key => {
const oldValue = oldObject[key];
const newValue = newObject[key];
if (newValue === undefined && oldValue !== undefined) {
diff.removed[key] = undefined;
}
});
return diff;
},
/**
* Return whether the two values are equal according to the `==` operator.
*
* @example
* import { utils } from 'js-data';
* console.log(utils.equal(1,1)); // true
* console.log(utils.equal(1,'1')); // true
* console.log(utils.equal(93, 66)); // false
*
* @method utils.equal
* @param {*} a First value in the comparison.
* @param {*} b Second value in the comparison.
* @returns {boolean} Whether the two values are equal according to `==`.
* @since 3.0.0
*/
equal(a, b) {
// tslint:disable-next-line:triple-equals
return a == b; // eslint-disable-line
},
/**
* Produce a factory function for making Error objects with the provided
* metadata. Used throughout the various js-data components.
*
* @example
* import { utils } from 'js-data';
* const errorFactory = utils.err('domain', 'target');
* const error400 = errorFactory(400, 'expected type', 'actual type');
* console.log(error400); // [Error: [domain:target] expected: expected type, found: string
* http://www.js-data.io/v3.0/docs/errors#400]
* @method utils.err
* @param {string} domain Namespace.
* @param {string} target Target.
* @returns {Function} Factory function.
* @since 3.0.0
*/
err(domain, target) {
return (code, ...args) => {
const prefix = `[${domain}:${target}] `;
let message = ERRORS[code].apply(null, args);
message = `${prefix}${message}
http://www.js-data.io/v3.0/docs/errors#${code}`;
return new Error(message);
};
},
/**
* Add eventing capabilities into the target object.
*
* @example
* import { utils } from 'js-data';
* const user = { name: 'John' };
* utils.eventify(user);
* user.on('foo', () => console.log(arguments));
* user.emit('foo', 1, 'bar'); // should log to console values (1, "bar")
*
* @method utils.eventify
* @param {object} target Target object.
* @param {Function} [getter] Custom getter for retrieving the object's event
* listeners.
* @param {Function} [setter] Custom setter for setting the object's event
* listeners.
* @since 3.0.0
*/
eventify(target, getter, setter) {
target = target || this;
let _events = {};
if (!getter && !setter) {
getter = () => _events;
setter = value => (_events = value);
}
Object.defineProperties(target, {
emit: {
value(...args) {
const events = getter.call(this) || {};
const type = args.shift();
let listeners = events[type] || [];
let i;
for (i = 0; i < listeners.length; i++) {
listeners[i].f.apply(listeners[i].c, args);
}
listeners = events.all || [];
args.unshift(type);
for (i = 0; i < listeners.length; i++) {
listeners[i].f.apply(listeners[i].c, args);
}
}
},
off: {
value(type, func) {
const events = getter.call(this);
const listeners = events[type];
if (!listeners) {
setter.call(this, {});
}
else if (func) {
for (let i = 0; i < listeners.length; i++) {
if (listeners[i].f === func) {
listeners.splice(i, 1);
break;
}
}
}
else {
listeners.splice(0, listeners.length);
}
}
},
on: {
value(type, func, thisArg) {
if (!getter.call(this)) {
setter.call(this, {});
}
const events = getter.call(this);
events[type] = events[type] || [];
events[type].push({
c: thisArg,
f: func
});
}
}
});
},
/**
* Shallow copy own enumerable properties from `src` to `dest` that are on
* `src` but are missing from `dest.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: 'bar', beep: 'boop' };
* const b = { beep: 'bip' };
* utils.fillIn(b, a);
* console.log(b); // {"foo":"bar","beep":"bip"}
*
* @method utils.fillIn
* @param {object} dest The destination object.
* @param src
* @see utils.deepFillIn
* @see utils.deepMixIn
* @since 3.0.0
*/
fillIn(dest, src) {
utils.forOwn(src, (value, key) => {
if (!dest.hasOwnProperty(key) || dest[key] === undefined) {
dest[key] = value;
}
});
},
/**
* Find the last index of an item in an array according to the given checker function.
*
* @example
* import { utils } from 'js-data';
*
* const john = { name: 'John', age: 20 };
* const sara = { name: 'Sara', age: 25 };
* const dan = { name: 'Dan', age: 20 };
* const users = [john, sara, dan];
*
* console.log(utils.findIndex(users, (user) => user.age === 25)); // 1
* console.log(utils.findIndex(users, (user) => user.age > 19)); // 2
* console.log(utils.findIndex(users, (user) => user.name === 'John')); // 0
* console.log(utils.findIndex(users, (user) => user.name === 'Jimmy')); // -1
*
* @method utils.findIndex
* @param {array} array The array to search.
* @param {Function} fn Checker function.
* @returns {number} Index if found or -1 if not found.
* @since 3.0.0
*/
findIndex(array, fn) {
let index = -1;
if (!array) {
return index;
}
array.forEach((record, i) => {
if (fn(record)) {
index = i;
return false;
}
});
return index;
},
/**
* Recursively iterate over a {@link Mapper}'s relations according to
* `opts.with`.
*
* @method utils.forEachRelation
* @param {Mapper} mapper Mapper.
* @param {object} opts Configuration options.
* @param {Function} fn Callback function.
* @param {*} thisArg Execution context for the callback function.
* @since 3.0.0
*/
forEachRelation(mapper, opts, fn, thisArg) {
const relationList = mapper.relationList || [];
if (!relationList.length) {
return;
}
relationList.forEach(def => {
utils._forRelation(opts, def, fn, thisArg);
});
},
/**
* Iterate over an object's own enumerable properties.
*
* @example
* import { utils } from 'js-data';
* const a = { b: 1, c: 4 };
* let sum = 0;
* utils.forOwn(a, function (value, key) {
* sum += value;
* });
* console.log(sum); // 5
*
* @method utils.forOwn
* @param obj
* @param {Function} fn Iteration function.
* @param {object} [thisArg] Content to which to bind `fn`.
* @since 3.0.0
*/
forOwn(obj, fn, thisArg) {
const keys = Object.keys(obj);
const len = keys.length;
let i;
for (i = 0; i < len; i++) {
if (fn.call(thisArg, obj[keys[i]], keys[i], obj) === false) {
break;
}
}
},
/**
* Proxy for `JSON.parse`.
*
* @example
* import { utils } from 'js-data';
*
* const a = utils.fromJson('{"name" : "John"}');
* console.log(a); // { name: 'John' }
*
* @method utils.fromJson
* @param {string} json JSON to parse.
* @returns {Object} Parsed object.
* @see utils.toJson
* @since 3.0.0
*/
fromJson(json) {
return utils.isString(json) ? JSON.parse(json) : json;
},
/**
* Retrieve the specified property from the given object. Supports retrieving
* nested properties.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' }, beep: 'boop' };
* console.log(utils.get(a, 'beep')); // "boop"
* console.log(utils.get(a, 'foo.bar')); // "baz"
*
* @method utils.get
* @param {object} object Object from which to retrieve a property's value.
* @param {string} prop Property to retrieve.
* @returns {*} Value of the specified property.
* @see utils.set
* @since 3.0.0
*/
get(object, prop) {
if (!prop) {
return;
}
const parts = prop.split('.');
const last = parts.pop();
while ((prop = parts.shift())) {
// eslint-disable-line
object = object[prop];
if (object == null) {
// eslint-disable-line
return;
}
}
return object[last];
},
/**
* Return the superclass for the given instance or subclass. If an instance is
* provided, then finds the parent class of the instance's constructor.
*
* @example
* import { utils } from 'js-data';
* // using ES2015 classes
* class Foo {}
* class Bar extends Foo {}
* const barInstance = new Bar();
* let baseType = utils.getSuper(barInstance);
* console.log(Foo === baseType); // true
*
* // using Function constructor with utils.extend
* function Foo () {}
* Foo.extend = utils.extend;
* const Bar = Foo.extend();
* const barInstance = new Bar();
* let baseType = utils.getSuper(barInstance);
* console.log(Foo === baseType); // true
*
* @method utils.getSuper
* @param {Object|Function} instance Instance or constructor.
* @param {boolean} [isCtor=false] Whether `instance` is a constructor.
* @returns {Constructor} The superclass (grandparent constructor).
* @since 3.0.0
*/
getSuper(instance, isCtor) {
const ctor = isCtor ? instance : instance.constructor;
if (ctor.hasOwnProperty('__super__')) {
return ctor.__super__;
}
return Object.getPrototypeOf(ctor) || ctor.__proto__; // eslint-disable-line
},
/**
* Return the intersection of two arrays.
*
* @example
* import { utils } from 'js-data';
* const arrA = ['green', 'red', 'blue', 'red'];
* const arrB = ['green', 'yellow', 'red'];
* const intersected = utils.intersection(arrA, arrB);
*
* console.log(intersected); // ['green', 'red'])
*
* @method utils.intersection
* @param {array} array1 First array.
* @param {array} array2 Second array.
* @returns {Array} Array of elements common to both arrays.
* @since 3.0.0
*/
intersection(array1, array2) {
if (!array1 || !array2) {
return [];
}
array1 = Array.isArray(array1) ? array1 : [array1];
array2 = Array.isArray(array2) ? array2 : [array2];
const result = [];
let item;
let i;
const len = array1.length;
for (i = 0; i < len; i++) {
item = array1[i];
if (result.indexOf(item) !== -1) {
continue;
}
if (array2.indexOf(item) !== -1) {
result.push(item);
}
}
return result;
},
/**
* Proxy for `Array.isArray`.
*
* @example
* import { utils } from 'js-data';
* const a = [1,2,3,4,5];
* const b = { foo: "bar" };
* console.log(utils.isArray(a)); // true
* console.log(utils.isArray(b)); // false
*
* @method utils.isArray
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is an array.
* @since 3.0.0
*/
isArray: Array.isArray,
/**
* Return whether `prop` is matched by any string or regular expression in
* `blacklist`.
*
* @example
* import { utils } from 'js-data';
* const blacklist = [/^\$hashKey/g, /^_/g, 'id'];
* console.log(utils.isBlacklisted("$hashKey", blacklist)); // true
* console.log(utils.isBlacklisted("id", blacklist)); // true
* console.log(utils.isBlacklisted("_myProp", blacklist)); // true
* console.log(utils.isBlacklisted("my_id", blacklist)); // false
*
* @method utils.isBlacklisted
* @param {string} prop The name of a property to check.
* @param {array} blacklist Array of strings and regular expressions.
* @returns {boolean} Whether `prop` was matched.
* @since 3.0.0
*/
isBlacklisted(prop, blacklist) {
if (!blacklist || !blacklist.length) {
return false;
}
let matches;
for (const item of blacklist) {
if ((toStr(item) === REGEXP_TAG && item.test(prop)) || item === prop) {
matches = prop;
return !!matches;
}
}
return !!matches;
},
/**
* Return whether the provided value is a boolean.
*
* @example
* import { utils } from 'js-data';
* const a = true;
* const b = { foo: "bar" };
* console.log(utils.isBoolean(a)); // true
* console.log(utils.isBoolean(b)); // false
*
* @method utils.isBoolean
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is a boolean.
* @since 3.0.0
*/
isBoolean(value) {
return toStr(value) === BOOL_TAG;
},
/**
* Return whether the provided value is a date.
*
* @example
* import { utils } from 'js-data';
* const a = new Date();
* const b = { foo: "bar" };
* console.log(utils.isDate(a)); // true
* console.log(utils.isDate(b)); // false
*
* @method utils.isDate
* @param {*} value The value to test.
* @returns {Date} Whether the provided value is a date.
* @since 3.0.0
*/
isDate(value) {
return value && typeof value === 'object' && toStr(value) === DATE_TAG;
},
/**
* Return whether the provided value is a function.
*
* @example
* import { utils } from 'js-data';
* const a = function () { console.log('foo bar'); };
* const b = { foo: "bar" };
* console.log(utils.isFunction(a)); // true
* console.log(utils.isFunction(b)); // false
*
* @method utils.isFunction
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is a function.
* @since 3.0.0
*/
isFunction(value) {
return typeof value === 'function' || (value && toStr(value) === FUNC_TAG);
},
/**
* Return whether the provided value is an integer.
*
* @example
* import { utils } from 'js-data';
* const a = 1;
* const b = 1.25;
* const c = '1';
* console.log(utils.isInteger(a)); // true
* console.log(utils.isInteger(b)); // false
* console.log(utils.isInteger(c)); // false
*
* @method utils.isInteger
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is an integer.
* @since 3.0.0
*/
isInteger(value) {
// tslint:disable-next-line:triple-equals
return toStr(value) === NUMBER_TAG && value == toInteger(value); // eslint-disable-line
},
/**
* Return whether the provided value is `null`.
*
* @example
* import { utils } from 'js-data';
* const a = null;
* const b = { foo: "bar" };
* console.log(utils.isNull(a)); // true
* console.log(utils.isNull(b)); // false
*
* @method utils.isNull
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is `null`.
* @since 3.0.0
*/
isNull(value) {
return value === null;
},
/**
* Return whether the provided value is a number.
*
* @example
* import { utils } from 'js-data';
* const a = 1;
* const b = -1.25;
* const c = '1';
* console.log(utils.isNumber(a)); // true
* console.log(utils.isNumber(b)); // true
* console.log(utils.isNumber(c)); // false
*
* @method utils.isNumber
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is a number.
* @since 3.0.0
*/
isNumber(value) {
const type = typeof value;
return type === 'number' || (value && type === 'object' && toStr(value) === NUMBER_TAG);
},
/**
* Return whether the provided value is an object.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: "bar" };
* const b = 'foo bar';
* console.log(utils.isObject(a)); // true
* console.log(utils.isObject(b)); // false
*
* @method utils.isObject
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is an object.
* @since 3.0.0
*/
isObject(value) {
return toStr(value) === OBJECT_TAG;
},
/**
* Return whether the provided value is a regular expression.
*
* @example
* import { utils } from 'js-data';
* const a = /^\$.+$/ig;
* const b = new RegExp('^\$.+$', 'ig');
* const c = { foo: "bar" };
* console.log(utils.isRegExp(a)); // true
* console.log(utils.isRegExp(b)); // true
* console.log(utils.isRegExp(c)); // false
*
* @method utils.isRegExp
* @param {*} value The value to test.
* @returns {boolean} Whether the provided value is a regular expression.
* @since 3.0.0
*/
isRegExp(value) {
return toStr(value) === REGEXP_TAG;
},
/**
* Return whether the provided value is a string or a number.
*
* @example
* import { utils } from 'js-data';
* console.log(utils.isSorN('')); // true
* console.log(utils.isSorN(-1.65)); // true
* console.log(utils.isSorN('my string')); // true
* console.log(utils.isSorN({})); // false
* console.log(utils.isSorN([1,2,4])); // false
*
* @method utils.isSorN
* @param {*} value The value to test.