Skip to content

Commit

Permalink
feat(jexl): add flatten transform
Browse files Browse the repository at this point in the history
  • Loading branch information
anehx committed Jul 17, 2023
1 parent 88cc66d commit c53e0e3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
8 changes: 8 additions & 0 deletions packages/core/addon/utils/jexl.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ export const mapby = (arr, ...keys) => {
);
};

export const flatten = (array) => {
if (!Array.isArray(array)) {
return null;
}

return array.flat();
};

/**
* Transform a JEXL expression into it's AST
*
Expand Down
7 changes: 6 additions & 1 deletion packages/form/addon/lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import jexl from "jexl";
import { cached } from "tracked-toolbox";

import { decodeId } from "@projectcaluma/ember-core/helpers/decode-id";
import { intersects, mapby } from "@projectcaluma/ember-core/utils/jexl";
import {
intersects,
mapby,
flatten,
} from "@projectcaluma/ember-core/utils/jexl";
import Base from "@projectcaluma/ember-form/lib/base";

const onlyNumbers = (nums) =>
Expand Down Expand Up @@ -180,6 +184,7 @@ export default class Document extends Base {
return nums.length ? sum(nums) / nums.length : null;
});
documentJexl.addTransform("stringify", (input) => JSON.stringify(input));
documentJexl.addTransform("flatten", flatten);

return documentJexl;
}
Expand Down
17 changes: 16 additions & 1 deletion packages/form/tests/unit/lib/document-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ module("Unit | Library | document", function (hooks) {
);
});

test("it stringifies correctly", async function (assert) {
test("it transforms correcty with stringify transform", async function (assert) {
assert.true(
await this.document.jexl.eval(
'\'["test1","test2"]\' == value|stringify',
Expand All @@ -246,6 +246,21 @@ module("Unit | Library | document", function (hooks) {
);
});

test("it transforms correcty with flatten transform", async function (assert) {
const expression = "array|flatten";

assert.deepEqual(
await this.document.jexl.eval(expression, {
array: [["some-value"], ["some-other-value"]],
}),
["some-value", "some-other-value"]
);
assert.strictEqual(
await this.document.jexl.eval(expression, { array: null }),
null
);
});

test("computes the correct jexl context", async function (assert) {
assert.expect(1);

Expand Down

0 comments on commit c53e0e3

Please sign in to comment.