Skip to content

Commit

Permalink
feat: Add ability to specify arbitrary aggregations in json (#250)
Browse files Browse the repository at this point in the history
* feat: Add ability to specify arbitrary aggregations in json

* jheer comments
  • Loading branch information
frtennis1 authored Jan 11, 2024
1 parent 1faee8b commit a987652
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
14 changes: 10 additions & 4 deletions packages/vgplot/src/spec/parse-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ export class ParseContext {

maybeTransform(value) {
if (isObject(value)) {
return value.expr
? parseExpression(value, this)
return value.expr ? parseExpression(value, this)
: value.agg ? parseAggregation(value, this)
: parseTransform(value, this);
}
}
Expand Down Expand Up @@ -363,8 +363,9 @@ function parseInteractor(spec, ctx) {
return fn(options);
}

function parseExpression(spec, ctx) {
const { expr, label } = spec;
function parseExpression(spec, ctx, key = 'expr') {
const { label } = spec;
const expr = spec[key];
const tokens = expr.split(/(\\'|\\"|"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|\$\w+)/g);
const spans = [''];
const exprs = [];
Expand All @@ -382,6 +383,11 @@ function parseExpression(spec, ctx) {
return sql(spans, ...exprs).annotate({ label });
}

function parseAggregation(spec, ctx) {
return parseExpression(spec, ctx, 'agg').annotate({aggregate: true});
}


function parseTransform(spec, ctx) {
const { transforms } = ctx;
let name;
Expand Down
11 changes: 6 additions & 5 deletions packages/vgplot/src/spec/to-module.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ class CodegenContext extends ParseContext {

maybeTransform(value) {
if (isObject(value)) {
return value.expr
? parseExpression(value, this)
return value.expr ? parseExpression(value, this)
: value.agg ? parseExpression(value, this, 'agg', 'agg')
: parseTransform(value, this);
}
}
Expand All @@ -162,8 +162,9 @@ class CodegenContext extends ParseContext {
}
}

function parseExpression(spec, ctx) {
const { expr, label } = spec;
function parseExpression(spec, ctx, key = 'expr', method = 'sql') {
const { label } = spec;
const expr = spec[key]
const tokens = expr.split(/(\\'|\\"|"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|\$\w+)/g);
let str = '';

Expand All @@ -176,7 +177,7 @@ function parseExpression(spec, ctx) {
}
}

return `vg.sql\`${str}\``
return `vg.${method}\`${str}\``
+ (label ? `.annotate({ label: ${JSON.stringify(label)} })` : '');
}

Expand Down

0 comments on commit a987652

Please sign in to comment.