forked from misoproject/dataset
-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.js
710 lines (591 loc) · 18.9 KB
/
view.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
(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 (this.data[j] !== null) {
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 (this.data[j] !== null) {
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.filter = options.filter || {};
if ( _.isFunction(filter) ) {
options.filter.rows = filter;
} else {
options.filter = filter;
}
options.parent = this;
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 all rows in the dataset in reverse order
* Parameters:
* iterator - function that is passed each row
* iterator(rowObject, index, dataset)
* context - options object. Optional.
*/
reverseEach : function(iterator, context) {
for(var i = this.length-1; i >= 0; 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
this._rowIdByPosition = this._rowIdByPosition || (this._rowIdByPosition = []);
this._rowPositionById = this._rowPositionById || (this._rowPositionById = {});
this._rowIdByPosition.push(row._id);
this._rowPositionById[row._id] = this._rowIdByPosition.length;
// otherwise insert them in the right place. This is a somewhat
// expensive operation.
} else {
var insertAt = function(at, value, into) {
Array.prototype.splice.apply(into, [at, 0].concat(value));
};
var i;
this.length++;
for(i = 0; i < this.length; i++) {
var row2 = this.rowByPosition(i);
if (_.isUndefined(row2._id) || this.comparator(row, row2) < 0) {
_.each(this._columns, function(column) {
insertAt(i, (row[column.name] ? row[column.name] : null), column.data);
});
break;
}
}
// rebuild position cache...
// we could splice it in but its safer this way.
this._rowIdByPosition = [];
this._rowPositionById = {};
this.each(function(row, i) {
this._rowIdByPosition.push(row._id);
this._rowPositionById[row._id] = i;
});
}
return this;
},
/**
* Returns a dataset view of filtered rows
* @param {function|array} filter - a filter function or object,
* the same as where
*/
rows : function(filter) {
return new Miso.DataView({
filter : { rows : filter },
parent : this
});
},
/**
* Sort rows based on comparator
*
* roughly taken from here:
* http://jxlib.googlecode.com/svn-history/r977/trunk/src/Source/Data/heapsort.js
* License:
* Copyright (c) 2009, Jon Bomgardner.
* This file is licensed under an MIT style license
* Parameters:
* options - Optional
*/
sort : function(args) {
var options = {};
//If the first param is the comparator, set it as such.
if ( _.isFunction(args) ) {
options.comparator = args;
} else {
options = args || options;
}
if (options.comparator) {
this.comparator = options.comparator;
}
if (_.isUndefined(this.comparator)) {
throw new Error("Cannot sort without this.comparator.");
}
var count = this.length, end;
if (count === 1) {
// we're done. only one item, all sorted.
return;
}
var swap = _.bind(function(from, to) {
// move second row over to first
var row = this.rowByPosition(to);
_.each(row, function(value, column) {
var colPosition = this._columnPositionByName[column],
value2 = this._columns[colPosition].data[from];
this._columns[colPosition].data.splice(from, 1, value);
this._columns[colPosition].data.splice(to, 1, value2);
}, this);
}, this);
var siftDown = _.bind(function(start, end) {
var root = start, child;
while (root * 2 <= end) {
child = root * 2;
var root_node = this.rowByPosition(root);
if ((child + 1 < end) &&
this.comparator(
this.rowByPosition(child),
this.rowByPosition(child+1)
) < 0) {
child++;
}
if (this.comparator(
root_node,
this.rowByPosition(child)) < 0) {
swap(root, child);
root = child;
} else {
return;
}
}
}, this);
// puts data in max-heap order
var heapify = function(count) {
var start = Math.round((count - 2) / 2);
while (start >= 0) {
siftDown(start, count - 1);
start--;
}
};
if (count > 2) {
heapify(count);
end = count - 1;
while (end > 1) {
swap(end, 0);
end--;
siftDown(0, end);
}
} else {
if (this.comparator(
this.rowByPosition(0),
this.rowByPosition(1)) > 0) {
swap(0,1);
}
}
// check last two rows, they seem to always be off sync.
if (this.comparator(
this.rowByPosition(this.length - 2),
this.rowByPosition(this.length - 1)) > 0) {
swap(this.length - 1,this.length - 2);
}
if (this.syncable && options.silent) {
this.trigger("sort");
}
return this;
},
/**
* Exports a version of the dataset in json format.
* Returns:
* Array of rows.
*/
toJSON : function() {
var rows = [];
for(var i = 0; i < this.length; i++) {
rows.push(this.rowByPosition(i));
}
return rows;
}
});
}(this, _));