UNPKG

1.46 kBJavaScriptView Raw
1import {Transform} from 'vega-dataflow';
2import {inherits} from 'vega-util';
3
4/**
5 * Invokes a function for each data tuple and saves the results as a new field.
6 * @constructor
7 * @param {object} params - The parameters for this operator.
8 * @param {function(object): *} params.expr - The formula function to invoke for each tuple.
9 * @param {string} params.as - The field name under which to save the result.
10 * @param {boolean} [params.initonly=false] - If true, the formula is applied to
11 * added tuples only, and does not update in response to modifications.
12 */
13export default function Formula(params) {
14 Transform.call(this, null, params);
15}
16
17Formula.Definition = {
18 'type': 'Formula',
19 'metadata': {'modifies': true},
20 'params': [
21 { 'name': 'expr', 'type': 'expr', 'required': true },
22 { 'name': 'as', 'type': 'string', 'required': true },
23 { 'name': 'initonly', 'type': 'boolean' }
24 ]
25};
26
27inherits(Formula, Transform, {
28 transform (_, pulse) {
29 const func = _.expr,
30 as = _.as,
31 mod = _.modified(),
32 flag = _.initonly ? pulse.ADD
33 : mod ? pulse.SOURCE
34 : pulse.modified(func.fields) || pulse.modified(as) ? pulse.ADD_MOD
35 : pulse.ADD;
36
37 if (mod) {
38 // parameters updated, need to reflow
39 pulse = pulse.materialize().reflow(true);
40 }
41
42 if (!_.initonly) {
43 pulse.modifies(as);
44 }
45
46 return pulse.visit(flag, t => t[as] = func(t, _));
47 }
48});