UNPKG

2.11 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
33inherits(Flatten, Transform, {
34 transform(_, pulse) {
35 const out = pulse.fork(pulse.NO_SOURCE),
36 fields = _.fields,
37 as = fieldNames(fields, _.as || []),
38 index = _.index || null,
39 m = as.length;
40
41 // remove any previous results
42 out.rem = this.value;
43
44 // generate flattened tuples
45 pulse.visit(pulse.SOURCE, t => {
46 const arrays = fields.map(f => f(t)),
47 maxlen = arrays.reduce((l, a) => Math.max(l, a.length), 0);
48 let i = 0, j, d, v;
49
50 for (; i<maxlen; ++i) {
51 d = derive(t);
52 for (j=0; j<m; ++j) {
53 d[as[j]] = (v = arrays[j][i]) == null ? null : v;
54 }
55 if (index) {
56 d[index] = i;
57 }
58 out.add.push(d);
59 }
60 });
61
62 this.value = out.source = out.add;
63 if (index) out.modifies(index);
64 return out.modifies(as);
65 }
66});