UNPKG

1.5 kBJavaScriptView Raw
1import {Transform, derive} from 'vega-dataflow';
2import {accessorName, inherits} from 'vega-util';
3
4/**
5 * Folds one more tuple fields into multiple tuples in which the field
6 * name and values are available under new 'key' and 'value' fields.
7 * @constructor
8 * @param {object} params - The parameters for this operator.
9 * @param {function(object): *} params.fields - An array of field accessors
10 * for the tuple fields that should be folded.
11 * @param {Array<string>} [params.as] - Output field names for folded key
12 * and value fields, defaults to ['key', 'value'].
13 */
14export default function Fold(params) {
15 Transform.call(this, [], params);
16}
17
18Fold.Definition = {
19 'type': 'Fold',
20 'metadata': {'generates': true},
21 'params': [
22 { 'name': 'fields', 'type': 'field', 'array': true, 'required': true },
23 { 'name': 'as', 'type': 'string', 'array': true, 'length': 2, 'default': ['key', 'value'] }
24 ]
25};
26
27inherits(Fold, Transform, {
28 transform(_, pulse) {
29 const out = pulse.fork(pulse.NO_SOURCE),
30 fields = _.fields,
31 fnames = fields.map(accessorName),
32 as = _.as || ['key', 'value'],
33 k = as[0],
34 v = as[1],
35 n = fields.length;
36
37 out.rem = this.value;
38
39 pulse.visit(pulse.SOURCE, t => {
40 for (let i=0, d; i<n; ++i) {
41 d = derive(t);
42 d[k] = fnames[i];
43 d[v] = fields[i](t);
44 out.add.push(d);
45 }
46 });
47
48 this.value = out.source = out.add;
49 return out.modifies(as);
50 }
51});