/
miso.ds.0.1.3.js
3213 lines (2601 loc) · 87.8 KB
/
miso.ds.0.1.3.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
/**
* Miso.Dataset - v0.1.3 - 5/23/2012
* http://github.com/misoproject/dataset
* Copyright (c) 2012 Alex Graul, Irene Ros;
* Dual Licensed: MIT, GPL
* https://github.com/misoproject/dataset/blob/master/LICENSE-MIT
* https://github.com/misoproject/dataset/blob/master/LICENSE-GPL
*/
(function(global, _) {
/* @exports namespace */
var Miso = global.Miso = {};
Miso.typeOf = function(value, options) {
var types = _.keys(Miso.types),
chosenType;
//move string and mixed to the end
types.push(types.splice(_.indexOf(types, 'string'), 1)[0]);
types.push(types.splice(_.indexOf(types, 'mixed'), 1)[0]);
chosenType = _.find(types, function(type) {
return Miso.types[type].test(value, options);
});
chosenType = _.isUndefined(chosenType) ? 'string' : chosenType;
return chosenType;
};
Miso.types = {
mixed : {
name : 'mixed',
coerce : function(v) {
return v;
},
test : function(v) {
return true;
},
compare : function(s1, s2) {
if (s1 < s2) { return -1; }
if (s1 > s2) { return 1; }
return 0;
},
numeric : function(v) {
return _.isNaN( Number(v) ) ? 0 : Number(v);
}
},
string : {
name : "string",
coerce : function(v) {
return v == null ? null : v.toString();
},
test : function(v) {
return (v === null || typeof v === "undefined" || typeof v === 'string');
},
compare : function(s1, s2) {
if (s1 == null && s2 != null) { return -1; }
if (s1 != null && s2 == null) { return 1; }
if (s1 < s2) { return -1; }
if (s1 > s2) { return 1; }
return 0;
},
numeric : function(value) {
return _.isNaN(+value) ? 0 : +value;
}
},
boolean : {
name : "boolean",
regexp : /^(true|false)$/,
coerce : function(v) {
if (v === 'false') { return false; }
return Boolean(v);
},
test : function(v) {
if (v === null || typeof v === "undefined" || typeof v === 'boolean' || this.regexp.test( v ) ) {
return true;
} else {
return false;
}
},
compare : function(n1, n2) {
if (n1 == null && n2 != null) { return -1; }
if (n1 != null && n2 == null) { return 1; }
if (n1 == null && n2 == null) { return 0; }
if (n1 === n2) { return 0; }
return (n1 < n2 ? -1 : 1);
},
numeric : function(value) {
return (value) ? 1 : 0;
}
},
number : {
name : "number",
regexp : /^[\-\.]?[0-9]+([\.][0-9]+)?$/,
coerce : function(v) {
if (_.isNull(v) || v === "") {
return null;
}
return _.isNaN(v) ? null : +v;
},
test : function(v) {
if (v === null || typeof v === "undefined" || typeof v === 'number' || this.regexp.test( v ) ) {
return true;
} else {
return false;
}
},
compare : function(n1, n2) {
if (n1 == null && n2 != null) { return -1; }
if (n1 != null && n2 == null) { return 1; }
if (n1 == null && n2 == null) { return 0; }
if (n1 === n2) { return 0; }
return (n1 < n2 ? -1 : 1);
},
numeric : function(value) {
return value;
}
},
time : {
name : "time",
format : "DD/MM/YYYY",
_formatLookup : [
['DD', "\\d{2}"],
['D' , "\\d{1}|\\d{2}"],
['MM', "\\d{2}"],
['M' , "\\d{1}|\\d{2}"],
['YYYY', "\\d{4}"],
['YY', "\\d{2}"],
['A', "[AM|PM]"],
['hh', "\\d{2}"],
['h', "\\d{1}|\\d{2}"],
['mm', "\\d{2}"],
['m', "\\d{1}|\\d{2}"],
['ss', "\\d{2}"],
['s', "\\d{1}|\\d{2}"],
['ZZ',"[-|+]\\d{4}"],
['Z', "[-|+]\\d{2}:\\d{2}"]
],
_regexpTable : {},
_regexp: function(format) {
//memoise
if (this._regexpTable[format]) {
return new RegExp(this._regexpTable[format], 'g');
}
//build the regexp for substitutions
var regexp = format;
_.each(this._formatLookup, function(pair) {
regexp = regexp.replace(pair[0], pair[1]);
}, this);
// escape all forward slashes
regexp = regexp.split("/").join("\\/");
// save the string of the regexp, NOT the regexp itself.
// For some reason, this resulted in inconsistant behavior
this._regexpTable[format] = regexp;
return new RegExp(this._regexpTable[format], 'g');
},
coerce : function(v, options) {
options = options || {};
// if string, then parse as a time
if (_.isString(v)) {
var format = options.format || this.format;
return moment(v, options.format);
} else if (_.isNumber(v)) {
return moment(v);
} else {
return v;
}
},
test : function(v, options) {
options = options || {};
if (v === null || typeof v === "undefined") {
return true;
}
if (_.isString(v) ) {
var format = options.format || this.format,
regex = this._regexp(format);
return regex.test(v);
} else {
//any number or moment obj basically
return true;
}
},
compare : function(d1, d2) {
if (d1 < d2) {return -1;}
if (d1 > d2) {return 1;}
return 0;
},
numeric : function( value ) {
return value.valueOf();
}
}
};
}(this, _));
(function(global, _) {
var Miso = global.Miso || (global.Miso = {});
/**
* A representation of an event as it is passed through the
* system. Used for view synchronization and other default
* CRUD ops.
* Parameters:
* deltas - array of deltas.
* each delta: { changed : {}, old : {} }
*/
Miso.Event = function(deltas) {
if (!_.isArray(deltas)) {
deltas = [deltas];
}
this.deltas = deltas;
};
_.extend(Miso.Event.prototype, {
affectedColumns : function() {
var cols = [];
_.each(this.deltas, function(delta) {
delta.old = (delta.old || []);
delta.changed = (delta.changed || []);
cols = _.chain(cols)
.union(_.keys(delta.old), _.keys(delta.changed) )
.reject(function(col) {
return col === '_id';
}).value();
});
return cols;
}
});
_.extend(Miso.Event, {
/**
* Returns true if the event is a deletion
*/
isRemove : function(delta) {
if (_.isUndefined(delta.changed) || _.keys(delta.changed).length === 0) {
return true;
} else {
return false;
}
},
/**
* Returns true if the event is an add event.
*/
isAdd : function(delta) {
if (_.isUndefined(delta.old) || _.keys(delta.old).length === 0) {
return true;
} else {
return false;
}
},
/**
* Returns true if the event is an update.
*/
isUpdate : function(delta) {
if (!this.isRemove(delta) && !this.isAdd(delta)) {
return true;
} else {
return false;
}
}
});
//Event Related Methods
Miso.Events = {};
/**
* Bind callbacks to dataset events
* Parameters:
* ev - name of the event
* callback - callback function
* context - context for the callback. optional.
* Returns
* object being bound to.
*/
Miso.Events.bind = function (ev, callback, context) {
var calls = this._callbacks || (this._callbacks = {});
var list = calls[ev] || (calls[ev] = {});
var tail = list.tail || (list.tail = list.next = {});
tail.callback = callback;
tail.context = context;
list.tail = tail.next = {};
return this;
};
/**
* Remove one or many callbacks. If `callback` is null, removes all
* callbacks for the event. If `ev` is null, removes all bound callbacks
* for all events.
* Parameters:
* ev - event name
* callback - Optional. callback function to be removed
* Returns:
* The object being unbound from.
*/
Miso.Events.unbind = function(ev, callback) {
var calls, node, prev;
if (!ev) {
this._callbacks = null;
} else if (calls = this._callbacks) {
if (!callback) {
calls[ev] = {};
} else if (node = calls[ev]) {
while ((prev = node) && (node = node.next)) {
if (node.callback !== callback) {
continue;
}
prev.next = node.next;
node.context = node.callback = null;
break;
}
}
}
return this;
};
/**
* trigger a given event
* Parameters:
* eventName - name of event
* Returns;
* object being triggered on.
*/
Miso.Events.trigger = function(eventName) {
var node, calls, callback, args, ev, events = ['all', eventName];
if (!(calls = this._callbacks)) {
return this;
}
while (ev = events.pop()) {
if (!(node = calls[ev])) {
continue;
}
args = ev === 'all' ? arguments : Array.prototype.slice.call(arguments, 1);
while (node = node.next) {
if (callback = node.callback) {
callback.apply(node.context || this, args);
}
}
}
return this;
};
// Used to build event objects accross the application.
Miso.Events._buildEvent = function(delta) {
return new Miso.Event(delta);
};
}(this, _));
(function(global, _) {
var Miso = global.Miso || {};
/**
* This is a generic collection of dataset-building utilities
* that are used by Miso.Dataset and Miso.DataView.
*/
Miso.Builder = {
/**
* Detects the type of a column based on some input data.
* Parameters:
* column - the Miso.Column object
* data - an array of data to be scanned for type detection
* Returns:
* input column but typed.
*/
detectColumnType : function(column, data) {
// compute the type by assembling a sample of computed types
// and then squashing it to create a unique subset.
var type = _.inject(data.slice(0, 5), function(memo, value) {
var t = Miso.typeOf(value);
if (value !== "" && memo.indexOf(t) === -1 && !_.isNull(value)) {
memo.push(t);
}
return memo;
}, []);
// if we only have one type in our sample, save it as the type
if (type.length === 1) {
column.type = type[0];
} else {
//empty column or mixed type
column.type = 'mixed';
}
return column;
},
/**
* Detects the types of all columns in a dataset.
* Parameters:
* dataset - the dataset to test the columns of
* parsedData - the data to check the type of
*/
detectColumnTypes : function(dataset, parsedData) {
_.each(parsedData, function(data, columnName) {
var column = dataset.column( columnName );
// check if the column already has a type defined
if ( column.type ) {
column.force = true;
return;
} else {
Miso.Builder.detectColumnType(column, data);
}
}, this);
},
/**
* Used by internal importers to cache the rows
* in quick lookup tables for any id based operations.
* also used by views to cache the new rows they get
* as a result of whatever filter created them.
*/
cacheRows : function(dataset) {
Miso.Builder.clearRowCache(dataset);
// cache the row id positions in both directions.
// iterate over the _id column and grab the row ids
_.each(dataset._columns[dataset._columnPositionByName._id].data, function(id, index) {
dataset._rowPositionById[id] = index;
dataset._rowIdByPosition.push(id);
}, dataset);
// cache the total number of rows. There should be same
// number in each column's data
var rowLengths = _.uniq( _.map(dataset._columns, function(column) {
return column.data.length;
}));
if (rowLengths.length > 1) {
throw new Error("Row lengths need to be the same. Empty values should be set to null." +
_.map(dataset._columns, function(c) { return c.data + "|||" ; }));
} else {
dataset.length = rowLengths[0];
}
},
/**
* Clears the row cache objects of a dataset
* Parameters:
* dataset - Miso.Dataset instance.
*/
clearRowCache : function(dataset) {
dataset._rowPositionById = {};
dataset._rowIdByPosition = [];
},
/**
* Caches the column positions by name
* Parameters:
* dataset - Miso.Dataset instance.
*/
cacheColumns : function(dataset) {
dataset._columnPositionByName = {};
_.each(dataset._columns, function(column, i) {
dataset._columnPositionByName[column.name] = i;
});
}
};
// fix lack of IE indexOf. Again.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
};
}
}(this, _));
(function(global, _) {
var Miso = global.Miso;
/**
* A single column in a dataset
* Parameters:
* options
* name
* type (from Miso.types)
* data (optional)
* before (a pre coercion formatter)
* format (for time type.)
* any additional arguments here..
* Returns:
* new Miso.Column
*/
Miso.Column = function(options) {
_.extend(this, options);
this._id = options.id || _.uniqueId();
this.data = options.data || [];
return this;
};
_.extend(Miso.Column.prototype, {
/**
* Converts any value to this column's type for a given position
* in some source array.
* Parameters:
* value
* Returns:
* number
*/
toNumeric : function(value) {
return Miso.types[this.type].numeric(value);
},
/**
* Returns the numeric representation of a datum at any index in this
* column.
* Parameters:
* index - position in data array
* Returns
* number
*/
numericAt : function(index) {
return this.toNumeric(this.data[index]);
},
/**
* Coerces the entire column's data to the column type.
*/
coerce : function() {
this.data = _.map(this.data, function(datum) {
return Miso.types[this.type].coerce(datum, this);
}, this);
},
_sum : function() {
return _.sum(this.data);
},
_mean : function() {
var m = 0;
for (var j = 0; j < this.data.length; j++) {
m += this.numericAt(j);
}
m /= this.data.length;
return Miso.types[this.type].coerce(m, this);
},
_median : function() {
return Miso.types[this.type].coerce(_.median(this.data), this);
},
_max : function() {
var max = -Infinity;
for (var j = 0; j < this.data.length; j++) {
if (Miso.types[this.type].compare(this.data[j], max) > 0) {
max = this.numericAt(j);
}
}
return Miso.types[this.type].coerce(max, this);
},
_min : function() {
var min = Infinity;
for (var j = 0; j < this.data.length; j++) {
if (Miso.types[this.type].compare(this.data[j], min) < 0) {
min = this.numericAt(j);
}
}
return Miso.types[this.type].coerce(min, this);
}
});
/**
* Creates a new view.
* Parameters
* options - initialization parameters:
* parent : parent dataset
* filter : filter specification TODO: document better
* columns : column name or multiple names
* rows : rowId or function
* Returns
* new Miso.Dataview.
*/
Miso.DataView = function(options) {
if (typeof options !== "undefined") {
options = options || (options = {});
if (_.isUndefined(options.parent)) {
throw new Error("A view must have a parent specified.");
}
this.parent = options.parent;
this._initialize(options);
}
};
_.extend(Miso.DataView.prototype, {
_initialize: function(options) {
// is this a syncable dataset? if so, pull
// required methoMiso and mark this as a syncable dataset.
if (this.parent.syncable === true) {
_.extend(this, Miso.Events);
this.syncable = true;
}
// save filter
this.filter = {
columns : this._columnFilter(options.filter.columns || undefined),
rows : this._rowFilter(options.filter.rows || undefined)
};
// initialize columns.
this._columns = this._selectData();
Miso.Builder.cacheColumns(this);
Miso.Builder.cacheRows(this);
// bind to parent if syncable
if (this.syncable) {
this.parent.bind("change", this._sync, this);
}
},
// Syncs up the current view based on a passed delta.
_sync : function(event) {
var deltas = event.deltas, eventType = null;
// iterate over deltas and update rows that are affected.
_.each(deltas, function(d, deltaIndex) {
// find row position based on delta _id
var rowPos = this._rowPositionById[d._id];
// ===== ADD NEW ROW
if (typeof rowPos === "undefined" && Miso.Event.isAdd(d)) {
// this is an add event, since we couldn't find an
// existing row to update and now need to just add a new
// one. Use the delta's changed properties as the new row
// if it passes the filter.
if (this.filter.rows && this.filter.rows(d.changed)) {
this._add(d.changed);
eventType = "add";
}
} else {
//===== UPDATE EXISTING ROW
if (rowPos === "undefined") { return; }
// iterate over each changed property and update the value
_.each(d.changed, function(newValue, columnName) {
// find col position based on column name
var colPos = this._columnPositionByName[columnName];
if (_.isUndefined(colPos)) { return; }
this._columns[colPos].data[rowPos] = newValue;
eventType = "update";
}, this);
}
// ====== DELETE ROW (either by event or by filter.)
// TODO check if the row still passes filter, if not
// delete it.
var row = this.rowByPosition(rowPos);
// if this is a delete event OR the row no longer
// passes the filter, remove it.
if (Miso.Event.isRemove(d) ||
(this.filter.row && !this.filter.row(row))) {
// Since this is now a delete event, we need to convert it
// to such so that any child views, know how to interpet it.
var newDelta = {
_id : d._id,
old : this.rowByPosition(rowPos),
changed : {}
};
// replace the old delta with this delta
event.deltas.splice(deltaIndex, 1, newDelta);
// remove row since it doesn't match the filter.
this._remove(rowPos);
eventType = "delete";
}
}, this);
// trigger any subscribers
if (this.syncable) {
this.trigger(eventType, event);
this.trigger("change", event);
}
},
/**
* Returns a dataset view based on the filtration parameters
* Parameters:
* filter - object with optional columns array and filter object/function
* options - Options.
* Returns:
* new Miso.DataView
*/
where : function(filter, options) {
options = options || {};
options.parent = this;
options.filter = filter || {};
return new Miso.DataView(options);
},
_selectData : function() {
var selectedColumns = [];
_.each(this.parent._columns, function(parentColumn) {
// check if this column passes the column filter
if (this.filter.columns(parentColumn)) {
selectedColumns.push(new Miso.Column({
name : parentColumn.name,
data : [],
type : parentColumn.type,
_id : parentColumn._id
}));
}
}, this);
// get the data that passes the row filter.
this.parent.each(function(row) {
if (!this.filter.rows(row)) {
return;
}
for(var i = 0; i < selectedColumns.length; i++) {
selectedColumns[i].data.push(row[selectedColumns[i].name]);
}
}, this);
return selectedColumns;
},
/**
* Returns a normalized version of the column filter function
* that can be executed.
* Parameters:
* columnFilter - function or column name
*/
_columnFilter: function(columnFilter) {
var columnSelector;
// if no column filter is specified, then just
// return a passthrough function that will allow
// any column through.
if (_.isUndefined(columnFilter)) {
columnSelector = function() {
return true;
};
} else { //array
if (_.isString(columnFilter) ) {
columnFilter = [ columnFilter ];
}
columnFilter.push('_id');
columnSelector = function(column) {
return _.indexOf(columnFilter, column.name) === -1 ? false : true;
};
}
return columnSelector;
},
/**
* Returns a normalized row filter function
* that can be executed
*/
_rowFilter: function(rowFilter) {
var rowSelector;
//support for a single ID;
if (_.isNumber(rowFilter)) {
rowFilter = [rowFilter];
}
if (_.isUndefined(rowFilter)) {
rowSelector = function() {
return true;
};
} else if (_.isFunction(rowFilter)) {
rowSelector = rowFilter;
} else { //array
rowSelector = function(row) {
return _.indexOf(rowFilter, row._id) === -1 ? false : true;
};
}
return rowSelector;
},
/**
* Returns a dataset view of the given column name
* Parameters:
* name - name of the column to be selected
* Returns:
* Miso.Column.
*/
column : function(name) {
return this._column(name);
},
_column : function(name) {
if (_.isUndefined(this._columnPositionByName)) { return undefined; }
var pos = this._columnPositionByName[name];
return this._columns[pos];
},
/**
* Returns a dataset view of the given columns
* Parameters:
* columnsArray - an array of column names
* Returns:
* Miso.DataView.
*/
columns : function(columnsArray) {
return new Miso.DataView({
filter : { columns : columnsArray },
parent : this
});
},
/**
* Returns the names of all columns, not including id column.
* Returns:
* columnNames array
*/
columnNames : function() {
var cols = _.pluck(this._columns, 'name');
return _.reject(cols, function( colName ) {
return colName === '_id' || colName === '_oids';
});
},
/**
* Returns true if a column exists, false otherwise.
* Parameters:
* name (string)
* Returns
* true | false
*/
hasColumn : function(name) {
return (!_.isUndefined(this._columnPositionByName[name]));
},
/**
* Iterates over all rows in the dataset
* Paramters:
* iterator - function that is passed each row
* iterator(rowObject, index, dataset)
* context - options object. Optional.
*/
each : function(iterator, context) {
for(var i = 0; i < this.length; i++) {
iterator.apply(context || this, [this.rowByPosition(i), i]);
}
},
/**
* Iterates over each column.
* Parameters:
* iterator - function that is passed:
* iterator(colName, column, index)
* context - options object. Optional.
*/
eachColumn : function(iterator, context) {
// skip id col
var cols = this.columnNames();
for(var i = 0; i < cols.length; i++) {
iterator.apply(context || this, [cols[i], this.column(cols[i]), i]);
}
},
/**
* Returns a single row based on its position (NOT ID.)
* Paramters:
* i - position index
* Returns:
* row object representation
*/
rowByPosition : function(i) {
return this._row(i);
},
/**
* Returns a single row based on its id (NOT Position.)
* Parameters:
* id - unique id
* Returns:
* row object representation
*/
rowById : function(id) {
return this._row(this._rowPositionById[id]);
},
_row : function(pos) {
var row = {};
_.each(this._columns, function(column) {
row[column.name] = column.data[pos];
});
return row;
},
_remove : function(rowId) {
var rowPos = this._rowPositionById[rowId];
// remove all values
_.each(this._columns, function(column) {
column.data.splice(rowPos, 1);
});
// update caches
delete this._rowPositionById[rowId];
this._rowIdByPosition.splice(rowPos, 1);
this.length--;
return this;
},
_add : function(row, options) {
// first coerce all the values appropriatly
_.each(row, function(value, key) {
var column = this.column(key);
// if we suddenly see values for data that didn't exist before as a column
// just drop it. First fetch defines the column structure.
if (typeof column !== "undefined") {
var Type = Miso.types[column.type];
// test if value matches column type
if (column.force || Type.test(row[column.name], column)) {
// do we have a before filter? If so, pass it through that first
if (!_.isUndefined(column.before)) {
row[column.name] = column.before(row[column.name]);
}
// coerce it.
row[column.name] = Type.coerce(row[column.name], column);
} else {
throw("incorrect value '" + row[column.name] +
"' of type " + Miso.typeOf(row[column.name], column) +
" passed to column with type " + column.type);
}
}
}, this);
// if we don't have a comparator, just append them at the end.
if (_.isUndefined(this.comparator)) {
// add all data
_.each(this._columns, function(column) {
column.data.push(!_.isUndefined(row[column.name]) && !_.isNull(row[column.name]) ? row[column.name] : null);
});
this.length++;
// add row indeces to the cache