UNPKG

2.08 kBJavaScriptView Raw
1import {fieldNames} from './util/util';
2import {Transform, derive} from 'vega-dataflow';
3import {inherits} from 'vega-util';
4
5/**
6 * Flattens array-typed field values into new data objects.
7 * If multiple fields are specified, they are treated as parallel arrays,
8 * with output values included for each matching index (or null if missing).
9 * @constructor
10 * @param {object} params - The parameters for this operator.
11 * @param {Array<function(object): *>} params.fields - An array of field
12 * accessors for the tuple fields that should be flattened.
13 * @param {string} [params.index] - Optional output field name for index
14 * value. If unspecified, no index field is included in the output.
15 * @param {Array<string>} [params.as] - Output field names for flattened
16 * array fields. Any unspecified fields will use the field name provided
17 * by the fields accessors.
18 */
19export default function Flatten(params) {
20 Transform.call(this, [], params);
21}
22
23Flatten.Definition = {
24 'type': 'Flatten',
25 'metadata': {'generates': true},
26 'params': [
27 { 'name': 'fields', 'type': 'field', 'array': true, 'required': true },
28 { 'name': 'index', 'type': 'string' },
29 { 'name': 'as', 'type': 'string', 'array': true }
30 ]
31};
32
33var prototype = inherits(Flatten, Transform);
34
35prototype.transform = function(_, pulse) {
36 var out = pulse.fork(pulse.NO_SOURCE),
37 fields = _.fields,
38 as = fieldNames(fields, _.as || []),
39 index = _.index || null,
40 m = as.length;
41
42 // remove any previous results
43 out.rem = this.value;
44
45 // generate flattened tuples
46 pulse.visit(pulse.SOURCE, function(t) {
47 var arrays = fields.map(f => f(t)),
48 maxlen = arrays.reduce((l, a) => Math.max(l, a.length), 0),
49 i = 0, j, d, v;
50
51 for (; i<maxlen; ++i) {
52 d = derive(t);
53 for (j=0; j<m; ++j) {
54 d[as[j]] = (v = arrays[j][i]) == null ? null : v;
55 }
56 if (index) {
57 d[index] = i;
58 }
59 out.add.push(d);
60 }
61 });
62
63 this.value = out.source = out.add;
64 if (index) out.modifies(index);
65 return out.modifies(as);
66};