UNPKG

1.49 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
27var prototype = inherits(Fold, Transform);
28
29prototype.transform = function(_, pulse) {
30 var out = pulse.fork(pulse.NO_SOURCE),
31 fields = _.fields,
32 fnames = fields.map(accessorName),
33 as = _.as || ['key', 'value'],
34 k = as[0],
35 v = as[1],
36 n = fields.length;
37
38 out.rem = this.value;
39
40 pulse.visit(pulse.SOURCE, function(t) {
41 for (var i=0, d; i<n; ++i) {
42 d = derive(t);
43 d[k] = fnames[i];
44 d[v] = fields[i](t);
45 out.add.push(d);
46 }
47 });
48
49 this.value = out.source = out.add;
50 return out.modifies(as);
51};