Skip to content

Commit

Permalink
[Lens] Error on array values in math
Browse files Browse the repository at this point in the history
  • Loading branch information
wylieconlon committed Jun 16, 2021
1 parent 8abb656 commit 27603fd
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,21 +73,27 @@ export const mathColumn: ExpressionFunctionDefinition<
}

const newRows = input.rows.map((row) => {
return {
...row,
[args.id]: math.fn(
{
type: 'datatable',
columns: input.columns,
rows: [row],
},
{
expression: args.expression,
onError: args.onError,
},
context
),
};
const result = math.fn(
{
type: 'datatable',
columns: input.columns,
rows: [row],
},
{
expression: args.expression,
onError: args.onError,
},
context
);

if (Array.isArray(result)) {
if (result.length === 1) {
return { ...row, [args.id]: result[0] };
}
throw new Error(`Cannot perform math on array values at ${args.name}`);
}

return { ...row, [args.id]: result };
});
const type = newRows.length ? getType(newRows[0][args.id]) : 'null';
const newColumn: DatatableColumn = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,30 @@ describe('mathColumn', () => {
});
});

it('extracts a single array value, but not a multi-value array', () => {
const arrayTable = {
...testTable,
rows: [
{
name: 'product1',
time: 1517842800950, // 05 Feb 2018 15:00:00 GMT
price: [605, 500],
quantity: [100],
in_stock: true,
},
],
};
const args = {
id: 'output',
name: 'output',
expression: 'quantity',
};
expect(fn(arrayTable, args).rows[0].output).toEqual(100);
expect(() => fn(arrayTable, { ...args, expression: 'price' })).toThrowError(
`Cannot perform math on array values`
);
});

it('handles onError', () => {
const args = {
id: 'output',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ describe('getType()', () => {
});

test('throws if object has no .type property', () => {
expect(() => getType([])).toThrow();
expect(() => getType({})).toThrow();
expect(() => getType({ _type: 'foo' })).toThrow();
expect(() => getType({ tipe: 'foo' })).toThrow();
Expand Down
3 changes: 3 additions & 0 deletions src/plugins/expressions/common/expression_types/get_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

export function getType(node: any) {
if (node == null) return 'null';
if (Array.isArray(node)) {
throw new Error('Unexpected array value encountered.');
}
if (typeof node === 'object') {
if (!node.type) throw new Error('Objects must have a type property');
return node.type;
Expand Down

0 comments on commit 27603fd

Please sign in to comment.