-
Notifications
You must be signed in to change notification settings - Fork 4
/
nddb.js
executable file
·4604 lines (4240 loc) · 140 KB
/
nddb.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
/**
* # NDDB: N-Dimensional Database
* Copyright(c) 2021 Stefano Balietti <[email protected]>
* MIT Licensed
*
* NDDB is a powerful and versatile object database for node.js and the browser.
* ---
*/
(function(J) {
"use strict";
if ('undefined' !== typeof module &&
'undefined' !== typeof module.exports) {
J = module.parent.exports.JSUS || require('JSUS').JSUS;
module.exports = NDDB;
// Backward compatibility.
module.exports.NDDB = NDDB;
}
else {
J = JSUS;
window.NDDB = NDDB;
}
if (!J) throw new Error('NDDB: missing dependency: JSUS.');
/**
* ### df
*
* Flag indicating support for method Object.defineProperty
*
* If support is missing, the index `_nddbid` will be as a normal
* property, and, therefore, it will be enumerable.
*
* @see nddb_insert
* JSUS.compatibility
*/
var df = J.compatibility().defineProperty;
/**
* ### NDDB.db
*
* Returns a new db
*
* @param {object} options Optional. Configuration options
* @param {db} db Optional. An initial set of items to import
*
* @return {object} A new database
*/
NDDB.db = function(opts, db) { return new NDDB(opts, db); };
// Might get overwritten in index.js.
NDDB.lineBreak = '\n';
/**
* ### NDDB.decycle
*
* Removes cyclic references from an object
*
* @param {object} e The object to decycle
*
* @return {object} e The decycled object
*
* @see https://github.com/douglascrockford/JSON-js/
*/
NDDB.decycle = function(e) {
if (JSON && 'function' === typeof JSON.decycle) {
e = JSON.decycle(e);
}
return e;
};
/**
* ### NDDB.retrocycle
*
* Restores cyclic references in an object previously decycled
*
* @param {object} e The object to retrocycle
*
* @return {object} e The retrocycled object
*
* @see https://github.com/douglascrockford/JSON-js/
*/
NDDB.retrocycle = function(e) {
if (JSON && 'function' === typeof JSON.retrocycle) {
e = JSON.retrocycle(e);
}
return e;
};
/**
* ## NDDB constructor
*
* Creates a new instance of NDDB
*
* @param {object} options Optional. Configuration options
* @param {db} db Optional. An initial set of items to import
*/
function NDDB(opts, db) {
var that;
that = this;
opts = opts || {};
// ## Public properties.
this.name = opts.name || 'nddb';
// ### nddbid
// A global index of all objects.
this.nddbid = new NDDBIndex('nddbid', this);
// ### db
// The default database.
this.db = [];
// ### lastSelection
// The subset of items that were selected during the last operation
// Notice: some of the items might not exist any more in the database.
// @see NDDB.fetch
this.lastSelection = [];
// ### nddbid
// A global index of all hashed objects
// @see NDDBHashtray
this.hashtray = new NDDBHashtray();
// ###tags
// The tags list.
this.tags = {};
// ### hooks
// The list of hooks and associated callbacks
this.hooks = {
insert: [],
remove: [],
update: [],
setwd: [],
save: [],
load: []
};
// ### sharedHooks
// The list of hooks and associated callbacks shared with child database
// @experimental
this.sharedHooks = {
insert: [],
remove: [],
update: [],
setwd: [],
save: [],
load: []
};
// ### nddb_pointer
// Pointer for iterating along all the elements
this.nddb_pointer = 0;
// ### query
// QueryBuilder obj
// @see QueryBuilder
this.query = new QueryBuilder();
// ### filters
// Available db filters
this.filters = {};
this.addDefaultFilters();
// ### __userDefinedFilters
// Filters that are defined with addFilter
// The field is needed by cloneSettings
// @see NDDB.addFilter
this.__userDefinedFilters = {};
// ### __C
// List of comparator functions
this.__C = {};
// ### __H
// List of hash functions
this.__H = {};
// ### __I
// List of index functions
this.__I = {};
// ### __I
// List of view functions
this.__V = {};
// ### __update
// Auto update options container
this.__update = {};
// ### __update.pointer
// If TRUE, nddb_pointer always points to the last insert
this.__update.pointer = false;
// ### __update.indexes
// If TRUE, rebuild indexes on every insert and remove
this.__update.indexes = true;
// ### __update.sort
// If TRUE, sort db on every insert and remove
this.__update.sort = false;
// ### __shared
// Objects shared (not cloned) among breeded NDDB instances
this.__shared = {};
// ### __formats
// Currently supported formats for saving/loading items.
this.__formats = {};
// ### __defaultFormat
// Default format for saving and loading items.
this.__defaultFormat = null;
// ### __wd
// Default working directory for saving and loading files.
this.__wd = null;
// ### __parentDb
// The parent NDDB instance from which this db was created.
// Set in views and hashes.
// @experimental
this.__parentDb = null;
// ### log
// Std out for log messages
//
// It can be overriden in options by another function (`opts.log`).
// `opts.logCtx` specif the context of execution.
// @see NDDB.initLog
this.log = console.log;
// ### globalCompare
// Dummy compare function used to sort elements in the database
//
// It can be overriden with a compare function returning:
//
// - 0 if the objects are the same
// - a positive number if o2 precedes o1
// - a negative number if o1 precedes o2
//
this.globalCompare = function(o1, o2) {
return -1;
};
// Adding the "compareInAllFields" function.
//
// @see NDDB.comparator
this.comparator('*', function(o1, o2, trigger1, trigger2) {
var d, c, res;
for (d in o1) {
c = that.getComparator(d);
o2[d] = o2['*'];
res = c(o1, o2);
if (res === trigger1) return res;
if ('undefined' !== trigger2 && res === trigger2) return res;
// No need to delete o2[d] afer comparison.
}
// We are not interested in sorting.
// Figuring out the right return value.
if (trigger1 === 0) {
return trigger2 === 1 ? -1 : 1;
}
if (trigger1 === 1) {
return trigger2 === 0 ? -1 : 0;
}
return trigger2 === 0 ? 1 : 0;
});
// Add default formats (e.g. CSV, JSON in Node.js).
// See `/lib/fs.js`.
if ('function' === typeof this.addDefaultFormats) {
this.addDefaultFormats();
}
// Stores information about files saved (e.g., headers).
// Keys are filenames. There is one centeral cache for
// all hashes and views.
// @experimental.
this.__cache = {};
// Mixing in user options and defaults.
this.init(opts);
// Importing items, if any.
if (db) this.importDB(db);
if (opts.journal && 'function' === typeof NDDB.prototype.journal) {
this.journal({ filename: opts.journal, load: true, cb: opts.cb });
}
}
/**
* ### NDDB.addFilter
*
* Registers a _select_ function under an alphanumeric id
*
* When calling `NDDB.select('d','OP','value')` the second parameter (_OP_)
* will be matched with the callback function specified here.
*
* Callback function must accept three input parameters:
*
* - d: dimension of comparison
* - value: second-term of comparison
* - comparator: the comparator function as defined by `NDDB.comparator`
*
* and return a function that execute the desired operation.
*
* Registering a new filter with the same name of an already existing
* one, will overwrite the old filter without warnings.
*
* A reference to newly added filters are registered under
* `__userDefinedFilter`, so that they can be copied by `cloneSettings`.
*
* @param {string} op An alphanumeric id
* @param {function} cb The callback function
*
* @see QueryBuilder.addDefaultOperators
*/
NDDB.prototype.addFilter = function(op, cb) {
this.filters[op] = cb;
this.__userDefinedFilters[op] = this.filters[op];
};
/**
* ### NDDB.addDefaultFilters
*
* Register default filters for NDDB
*
* Default filters include standard logical operators:
*
* - '=', '==', '!=', ''>', >=', '<', '<=',
*
* and:
*
* - 'E': field exists (can be omitted, it is the default one)
* - '><': between values
* - '<>': not between values
* - 'in': element is found in array
* - '!in': element is noi found in array
* - 'LIKE': string SQL LIKE (case sensitive)
* - 'iLIKE': string SQL LIKE (case insensitive)
*
* @see NDDB.filters
*/
NDDB.prototype.addDefaultFilters = function() {
var that;
that = this;
// Exists.
this.filters['E'] = function(d, value, comparator) {
if ('object' === typeof d) {
return function(elem) {
var d, c;
for (d in elem) {
c = that.getComparator(d);
value[d] = value[0]['*'];
if (c(elem, value, 1) > 0) {
value[d] = value[1]['*'];
if (c(elem, value, -1) < 0) {
return elem;
}
}
}
if ('undefined' !== typeof elem[d]) {
return elem;
}
else if ('undefined' !== typeof J.getNestedValue(d,elem)) {
return elem;
}
};
}
else {
return function(elem) {
if ('undefined' !== typeof elem[d]) {
return elem;
}
else if ('undefined' !== typeof J.getNestedValue(d,elem)) {
return elem;
}
};
}
};
// (strict) Equals.
this.filters['=='] = function(d, value, comparator) {
return function(elem) {
if (comparator(elem, value, 0) === 0) return elem;
};
};
// (strict) Not Equals.
this.filters['!='] = function(d, value, comparator) {
return function(elem) {
if (comparator(elem, value, 0) !== 0) return elem;
};
};
// Smaller than.
this.filters['>'] = function(d, value, comparator) {
if ('object' === typeof d || d === '*') {
return function(elem) {
if (comparator(elem, value, 1) === 1) return elem;
};
}
else {
return function(elem) {
if ('undefined' === typeof elem[d]) return;
if (comparator(elem, value, 1) === 1) return elem;
};
}
};
// Greater than.
this.filters['>='] = function(d, value, comparator) {
if ('object' === typeof d || d === '*') {
return function(elem) {
var compared = comparator(elem, value, 0, 1);
if (compared === 1 || compared === 0) return elem;
};
}
else {
return function(elem) {
if ('undefined' === typeof elem[d]) return;
var compared = comparator(elem, value, 0, 1);
if (compared === 1 || compared === 0) return elem;
};
}
};
// Smaller than.
this.filters['<'] = function(d, value, comparator) {
if ('object' === typeof d || d === '*') {
return function(elem) {
if (comparator(elem, value, -1) === -1) return elem;
};
}
else {
return function(elem) {
if ('undefined' === typeof elem[d]) return;
if (comparator(elem, value, -1) === -1) return elem;
};
}
};
// Smaller or equal than.
this.filters['<='] = function(d, value, comparator) {
if ('object' === typeof d || d === '*') {
return function(elem) {
var compared = comparator(elem, value, 0, -1);
if (compared === -1 || compared === 0) return elem;
};
}
else {
return function(elem) {
if ('undefined' === typeof elem[d]) return;
var compared = comparator(elem, value, 0, -1);
if (compared === -1 || compared === 0) return elem;
};
}
};
// Between.
this.filters['><'] = function(d, value, comparator) {
if ('object' === typeof d) {
return function(elem) {
var i, len;
len = d.length;
for (i = 0; i < len ; i++) {
if (comparator(elem, value[0], 1) > 0 &&
comparator(elem, value[1], -1) < 0) {
return elem;
}
}
};
}
else if (d === '*') {
return function(elem) {
var d, c;
for (d in elem) {
c = that.getComparator(d);
value[d] = value[0]['*'];
if (c(elem, value, 1) > 0) {
value[d] = value[1]['*'];
if (c(elem, value, -1) < 0) {
return elem;
}
}
}
};
}
else {
return function(elem) {
if (comparator(elem, value[0], 1) > 0 &&
comparator(elem, value[1], -1) < 0) {
return elem;
}
};
}
};
// Not Between.
this.filters['<>'] = function(d, value, comparator) {
if ('object' === typeof d || d === '*') {
return function(elem) {
if (comparator(elem, value[0], -1) < 0 ||
comparator(elem, value[1], 1) > 0) {
return elem;
}
};
}
else {
return function(elem) {
if ('undefined' === typeof elem[d]) return;
if (comparator(elem, value[0], -1) < 0 ||
comparator(elem, value[1], 1) > 0) {
return elem;
}
};
}
};
// In Array.
this.filters['in'] = function(d, value, comparator) {
if ('object' === typeof d) {
return function(elem) {
var i, len;
len = value.length;
for (i = 0; i < len; i++) {
if (comparator(elem, value[i], 0) === 0) {
return elem;
}
}
};
}
else {
return function(elem) {
var i, obj, len;
obj = {}, len = value.length;
for (i = 0; i < len; i++) {
obj[d] = value[i];
if (comparator(elem, obj, 0) === 0) {
return elem;
}
}
};
}
};
// Not In Array.
this.filters['!in'] = function(d, value, comparator) {
if ('object' === typeof d) {
return function(elem) {
var i, len;
len = value.length;
for (i = 0; i < len; i++) {
if (comparator(elem, value[i], 0) === 0) {
return;
}
}
return elem;
};
}
else {
return function(elem) {
var i, obj, len;
obj = {}, len = value.length;
for (i = 0; i < len; i++) {
obj[d] = value[i];
if (comparator(elem, obj, 0) === 0) {
return;
}
}
return elem;
};
}
};
// Supports `_` and `%` wildcards.
function generalLike(d, value, comparator, sensitive) {
var regex;
RegExp.escape = function(str) {
return str.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
regex = RegExp.escape(value);
regex = regex.replace(/%/g, '.*').replace(/_/g, '.');
regex = new RegExp('^' + regex + '$', sensitive);
if ('object' === typeof d) {
return function(elem) {
var i, len;
len = d.length;
for (i = 0; i < len; i++) {
if ('undefined' !== typeof elem[d[i]]) {
if (regex.test(elem[d[i]])) {
return elem;
}
}
}
};
}
else if (d === '*') {
return function(elem) {
var d;
for (d in elem) {
if ('undefined' !== typeof elem[d]) {
if (regex.test(elem[d])) {
return elem;
}
}
}
};
}
else {
return function(elem) {
if ('undefined' !== typeof elem[d]) {
if (regex.test(elem[d])) {
return elem;
}
}
};
}
}
// Like operator (Case Sensitive).
this.filters['LIKE'] = function likeOperator(d, value, comparator) {
return generalLike(d, value, comparator);
};
// Like operator (Case Insensitive).
this.filters['iLIKE'] = function likeOperatorI(d, value, comparator) {
return generalLike(d, value, comparator, 'i');
};
};
// ## METHODS
/**
* ### NDDB.throwErr
*
* Throws an error with a predefined format
*
* The format is "constructor name" . "method name" : "error text" .
*
* It does **not** perform type checking on itw own input parameters.
*
* @param {string} type Optional. The error type, e.g. 'TypeError'.
* Default, 'Error'
* @param {string} method Optional. The name of the method
* @param {string|object} err Optional. The error. Default, 'generic error'
*/
NDDB.prototype.throwErr = function(type, method, err) {
var errMsg, text;
if ('object' === typeof err) text = err.stack || err;
else if ('string' === typeof err) text = err;
text = text || 'generic error';
errMsg = this._getConstrName();
if (method) errMsg = errMsg + '.' + method;
errMsg = errMsg + ': ' + text;
if (type === 'TypeError') throw new TypeError(errMsg);
throw new Error(errMsg);
};
/**
* ### NDDB.init
*
* Sets global options based on local configuration
*
* @param {object} options Optional. Configuration options
*
* TODO: type checking on input params
*/
NDDB.prototype.init = function(options) {
var filter, sh, i;
var errMsg;
options = options || {};
this.__options = options;
if (options.tags) {
if ('object' !== typeof options.tags) {
errMsg = 'options.tag must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
this.tags = options.tags;
}
if ('undefined' !== typeof options.nddb_pointer) {
if ('number' !== typeof options.nddb_pointer) {
errMsg = 'options.nddb_pointer must be number or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
this.nddb_pointer = options.nddb_pointer;
}
if (options.hooks) {
if ('object' !== typeof options.hooks) {
errMsg = 'options.hooks must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
for (i in options.hooks) {
if (options.hooks.hasOwnProperty(i)) {
if (!this.hooks[i]) {
errMsg = 'options.hooks unknown hook ' + i;
this.throwErr('TypeError', 'init', errMsg);
}
this.hooks[i] = options.hooks[i];
}
}
}
if (options.globalCompare) {
if ('function' !== typeof options.globalCompare) {
errMsg = 'options.globalCompare must be function or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
this.globalCompare = options.globalCompare;
}
if (options.update) {
if ('object' !== typeof options.update) {
errMsg = 'options.update must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
if ('undefined' !== typeof options.update.pointer) {
this.__update.pointer = options.update.pointer;
}
if ('undefined' !== typeof options.update.indexes) {
this.__update.indexes = options.update.indexes;
}
if ('undefined' !== typeof options.update.sort) {
this.__update.sort = options.update.sort;
}
}
if ('object' === typeof options.filters) {
if ('object' !== typeof options.filters) {
errMsg = 'options.filters must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
for (filter in options.filters) {
this.addFilter(filter, options.filters[filter]);
}
}
if ('object' === typeof options.shared) {
for (sh in options.shared) {
if (options.shared.hasOwnProperty(sh)) {
this.__shared[sh] = options.shared[sh];
}
}
}
// Delete the shared object, it must not be copied by _cloneSettings_.
delete this.__options.shared;
if (options.log) {
this.initLog(options.log, options.logCtx);
}
if (options.formats) {
if ('object' !== typeof options.formats) {
errMsg = 'options.formats must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
for (i in options.formats) {
if (options.formats.hasOwnProperty(i)) {
this.addFormat(i, options.formats[i]);
}
}
}
if (options.defaultFormat) {
this.setDefaultFormat(options.defaultFormat);
}
if (options.wd && 'function' === typeof this.setWD) {
this.setWD(options.wd);
}
// Below there might modifications to the options
// object via the cloneSettings method.
if (options.C) {
if ('object' !== typeof options.C) {
errMsg = 'options.C must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
this.__C = options.C;
}
if (options.H) {
if ('object' !== typeof options.H) {
errMsg = 'options.H must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
for (i in options.H) {
if (options.H.hasOwnProperty(i)) {
this.hash(i, options.H[i]);
}
}
}
if (options.I) {
if ('object' !== typeof options.I) {
errMsg = 'options.I must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
this.__I = options.I;
for (i in options.I) {
if (options.I.hasOwnProperty(i)) {
this.index(i, options.I[i]);
}
}
}
// Views must be created at the end because they are cloning
// all the previous settings (the method would also pollute
// this.__options if called before all options in init are set).
if (options.V) {
if ('object' !== typeof options.V) {
errMsg = 'options.V must be object or undefined';
this.throwErr('TypeError', 'init', errMsg);
}
this.__V = options.V;
for (i in options.V) {
if (options.V.hasOwnProperty(i)) {
this.view(i, options.V[i]);
}
}
}
};
/**
* ### NDDB.initLog
*
* Setups and external log function to be executed in the proper context
*
* @param {function} cb The logging function
* @param {object} ctx Optional. The context of the log function
*/
NDDB.prototype.initLog = function(cb, ctx) {
if ('function' !== typeof cb) {
this.throwErr('TypeError', 'initLog', 'cb must be function');
}
ctx = ctx || this;
if ('function' !== typeof ctx && 'object' !== typeof ctx) {
this.throwErr('TypeError', 'initLog', 'ctx must be object or ' +
'function');
}
this.log = function() {
var args, i, len;
len = arguments.length;
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
return cb.apply(ctx, args);
};
};
/**
* ### NDDB._getConstrName
*
* Returns 'NDDB' or the name of the inheriting class.
*/
NDDB.prototype._getConstrName = function() {
return this.constructor && this.constructor.name ?
this.constructor.name : 'NDDB';
};
// ## CORE
/**
* ### NDDB._autoUpdate
*
* Updates pointer, indexes, and sort items
*
* What is updated depends on configuration stored in `this.__update`.
*
* @param {object} options Optional. Configuration object
*
* @see NDDB.__update
*
* @api private
*/
NDDB.prototype._autoUpdate = function(options) {
var u;
u = this.__update;
options = options || {};
if (options.pointer ||
('undefined' === typeof options.pointer && u.pointer)) {
this.nddb_pointer = this.db.length-1;
}
if (options.sort ||
('undefined' === typeof options.sort && u.sort)) {
this.sort();
}
if (options.indexes ||
('undefined' === typeof options.indexes && u.indexes)) {
this.rebuildIndexes();
}
};
/**
* ### NDDB.importDB
*
* Imports an array of items at once
*
* @param {array} db Array of items to import
*/
NDDB.prototype.importDB = function(db) {
var i, len;
if (!J.isArray(db)) {
this.throwErr('TypeError', 'importDB', 'db must be array. Found: ' +
db);
}
i = -1, len = db.length;
for ( ; ++i < len ; ) {
nddb_insert.call(this, db[i], this.__update.indexes);
}
this._autoUpdate({indexes: false});
};
/**
* ### NDDB.insert
*
* Insert an item into the database
*
* Item must be of type object or function.
*
* The following entries will be ignored:
*
* - strings
* - numbers
* - undefined
* - null
*
* @param {object} o The item or array of items to insert
* @param {object} updateRules Optional. Update rules to overwrite
* system-wide settings stored in `this.__update`
*
* @return {object|boolean} o The inserted object (might have been
* updated by on('insert') callbacks), or FALSE if the object could
* not be inserted, e.g. if a on('insert') callback returned FALSE.
*
* @see NDDB.__update
* @see nddb_insert
*/
NDDB.prototype.insert = function(o, updateRules) {
var res;
if ('undefined' === typeof updateRules) {
updateRules = this.__update;
}
else if ('object' !== typeof updateRules) {
this.throwErr('TypeError', 'insert',
'updateRules must be object or undefined. Found: ',
updateRules);
}
res = nddb_insert.call(this, o, updateRules.indexes);
if (res === false) return false;
// If updateRules.indexes is false, then we do not want to do it.
// If it was true, we did it already.
this._autoUpdate({
indexes: false,
pointer: updateRules.pointer,
sort: updateRules.sort
});
return o;
};
/**
* ### NDDB.size
*
* Returns the number of elements in the database
*
* It always returns the length of the full database, regardless of
* current selection.
*
* @return {number} The total number of elements in the database
*
* @see NDDB.count
*/
NDDB.prototype.size = function() {