UNPKG

1.95 kBJavaScriptView Raw
1import {fieldNames} from './util/util';
2import {Transform, ingest, rederive, tupleid} from 'vega-dataflow';
3import {inherits} from 'vega-util';
4
5/**
6 * Performs a relational projection, copying selected fields from source
7 * tuples to a new set of derived tuples.
8 * @constructor
9 * @param {object} params - The parameters for this operator.
10 * @param {Array<function(object): *} params.fields - The fields to project,
11 * as an array of field accessors. If unspecified, all fields will be
12 * copied with names unchanged.
13 * @param {Array<string>} [params.as] - Output field names for each projected
14 * field. Any unspecified fields will use the field name provided by
15 * the field accessor.
16 */
17export default function Project(params) {
18 Transform.call(this, null, params);
19}
20
21Project.Definition = {
22 'type': 'Project',
23 'metadata': {'generates': true, 'changes': true},
24 'params': [
25 { 'name': 'fields', 'type': 'field', 'array': true },
26 { 'name': 'as', 'type': 'string', 'null': true, 'array': true }
27 ]
28};
29
30var prototype = inherits(Project, Transform);
31
32prototype.transform = function(_, pulse) {
33 var fields = _.fields,
34 as = fieldNames(_.fields, _.as || []),
35 derive = fields
36 ? function(s, t) { return project(s, t, fields, as); }
37 : rederive,
38 out, lut;
39
40 if (this.value) {
41 lut = this.value;
42 } else {
43 pulse = pulse.addAll();
44 lut = this.value = {};
45 }
46
47 out = pulse.fork(pulse.NO_SOURCE);
48
49 pulse.visit(pulse.REM, function(t) {
50 var id = tupleid(t);
51 out.rem.push(lut[id]);
52 lut[id] = null;
53 });
54
55 pulse.visit(pulse.ADD, function(t) {
56 var dt = derive(t, ingest({}));
57 lut[tupleid(t)] = dt;
58 out.add.push(dt);
59 });
60
61 pulse.visit(pulse.MOD, function(t) {
62 out.mod.push(derive(t, lut[tupleid(t)]));
63 });
64
65 return out;
66};
67
68function project(s, t, fields, as) {
69 for (var i=0, n=fields.length; i<n; ++i) {
70 t[as[i]] = fields[i](s);
71 }
72 return t;
73}