Skip to content

Commit

Permalink
feat(json-expression): 🎸 add values operator
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Aug 28, 2023
1 parent e713ece commit be2d0fa
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/json-expression/__tests__/jsonExpressionUnitTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1580,6 +1580,22 @@ export const jsonExpressionUnitTests = (
);
});
});

describe('values', () => {
test('returns empty array for empty object', () => {
check(['values', {}], []);
});

test('returns values of an object', () => {
check(['values', {foo: 1}], [1]);
});

test('throws on invalid operand count', () => {
expect(() => check(['values', 'a', 'b'] as any, false)).toThrowErrorMatchingInlineSnapshot(
`""values" operator expects 1 operands."`,
);
});
});
});

describe('Branching operators', () => {
Expand Down
15 changes: 15 additions & 0 deletions src/json-expression/operators/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,19 @@ export const objectOperators: types.OperatorDefinition<any>[] = [
return new Expression(js);
},
] as types.OperatorDefinition<types.ExprKeys>,

[
'values',
[],
1,
(expr: types.ExprValues, ctx) => {
const operand = ctx.eval(expr[1], ctx);
return util.values(operand);
},
(ctx: types.OperatorCodegenCtx<types.ExprValues>): ExpressionResult => {
ctx.link(util.values, 'values');
const js = `values(${ctx.operands[0]})`;
return new Expression(js);
},
] as types.OperatorDefinition<types.ExprValues>,
];
2 changes: 2 additions & 0 deletions src/json-expression/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,11 @@ export type ExprF64 = BinaryExpression<'f64'>;
// Object expressions
export type ObjectExpression =
| ExprKeys
| ExprValues
| ExprIn;

export type ExprKeys = UnaryExpression<'keys'>;
export type ExprValues = UnaryExpression<'values'>;
export type ExprIn = [fn: 'in', what: unknown, list: unknown];

// Bitwise expressions
Expand Down
8 changes: 8 additions & 0 deletions src/json-expression/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ export const asObj = (value: unknown): object => {
export const keys = (value: unknown): string[] =>
Object.keys(asObj(value));

export const values = (value: unknown): unknown[] => {
const values: unknown[] = [];
const theKeys = keys(value);
const length = theKeys.length;
for (let i = 0; i < length; i++) values.push((value as any)[theKeys[i]]);
return values;
};

export const u8 = (bin: unknown, pos: unknown) => {
const buf = asBin(bin);
const index = int(pos);
Expand Down

0 comments on commit be2d0fa

Please sign in to comment.