diff --git a/packages/core/addon/utils/jexl.js b/packages/core/addon/utils/jexl.js index 2117e9a9f..7016570cf 100644 --- a/packages/core/addon/utils/jexl.js +++ b/packages/core/addon/utils/jexl.js @@ -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 * diff --git a/packages/form/addon/lib/document.js b/packages/form/addon/lib/document.js index 35eca2333..60c00c35a 100644 --- a/packages/form/addon/lib/document.js +++ b/packages/form/addon/lib/document.js @@ -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) => @@ -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; } diff --git a/packages/form/tests/unit/lib/document-test.js b/packages/form/tests/unit/lib/document-test.js index 14f18bb90..5fe2f8963 100644 --- a/packages/form/tests/unit/lib/document-test.js +++ b/packages/form/tests/unit/lib/document-test.js @@ -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', @@ -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);