Skip to content

Commit 59abb96

Browse files
feat: new BADGE function (#20)
1 parent c13465d commit 59abb96

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/functions.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,12 @@ export function COALESCE(...args) {
1212
}
1313
}
1414
};
15+
16+
/**
17+
* Return the size on an array as text, with an optional given prefix/postfix
18+
*/
19+
export function BADGE(array, prefix = '', postfix = '') {
20+
const length = array?.length || '';
21+
if (length) return `${prefix}${length}${postfix}`;
22+
return '';
23+
}

test/index.test.js

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
import { describe, it } from "node:test";
32
import assert from "node:assert";
43

@@ -183,5 +182,45 @@ describe("flattenContext", () => {
183182
a_0__b_1__c_3: 25,
184183
},
185184
)
186-
})
185+
});
186+
});
187+
188+
describe("badge", () => {
189+
it("should return the length of an array or string", () => {
190+
const expression = `BADGE($var)`;
191+
const context = {$var: [100]};
192+
assert.equal(evaluate(expression, context), "1");
193+
const context2 = {$var: [1,2,3]};
194+
assert.equal(evaluate(expression, context2), "3");
195+
const context3 = {$var: 'hello'};
196+
assert.equal(evaluate(expression, context3), "5");
197+
const context4 = {$var: {"a": "1", "b": "2"}};
198+
assert.equal(evaluate(expression, context4), "");
199+
});
200+
it("should return 0 if the value is not an array or is empty or undefined", () => {
201+
const expression = `BADGE($var)`;
202+
const context = {$var: []};
203+
assert.equal(evaluate(expression, context), "");
204+
const context2 = {$var: undefined};
205+
assert.equal(evaluate(expression, context2), "");
206+
const context3 = {$var: 1};
207+
assert.equal(evaluate(expression, context3), "");
208+
});
209+
it("should return the length of an array, which is populated with objects", () => {
210+
const expression = `BADGE($local.add_media__media)`;
211+
const context = {
212+
$local: {
213+
add_media__media: [
214+
{ id: 1, name: "a" },
215+
{ id: 2, name: { abc: 1 }},
216+
]
217+
}
218+
};
219+
assert.equal(evaluate(expression, context), "2");
220+
});
221+
it("should include the given prefix/postfix when provided", () => {
222+
const expression = `BADGE($var,'count:[',']')`;
223+
const context = {$var: [100]};
224+
assert.equal(evaluate(expression, context), "count:[1]");
225+
});
187226
});

0 commit comments

Comments
 (0)