Skip to content

Commit aaf79e6

Browse files
committed
feat: add cases function
1 parent de50496 commit aaf79e6

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

packages/shared/widget-plugin-test-utils/__tests__/functions.test.ts

+38-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { listAttr, obj, ref, refSet, list, listAction, listRef, listRefSet } from "../src/main";
1+
import { listAttr, obj, ref, refSet, list, listAction, listRef, listRefSet, objArray, cases } from "../src/main";
22

33
describe("prop mocking functions", () => {
44
describe("list", () => {
@@ -146,4 +146,41 @@ describe("prop mocking functions", () => {
146146
});
147147
});
148148
});
149+
150+
describe("cases", () => {
151+
it("throw if there is no default case", () => {
152+
expect(() => {
153+
cases([obj(), ""]);
154+
}).toThrow();
155+
});
156+
157+
it("returns mapper that takes obj and returns value from the case", () => {
158+
const item = obj();
159+
const mapFn = cases([item, "item value"], [undefined, "None"]);
160+
expect(mapFn(item)).toBe("item value");
161+
});
162+
163+
it("use default case if item not found", () => {
164+
const mapFn = cases([obj(), "item value"], [undefined, "None"]);
165+
expect(mapFn(obj())).toBe("None");
166+
});
167+
168+
it("can work with listAttr", () => {
169+
const items = objArray(5);
170+
const [a, b, c] = items;
171+
const mapFn = cases([a, "Alice"], [b, "Bob"], [c, "Chuck"], [undefined, "None"]);
172+
const props = {
173+
datasource: list(items),
174+
name: listAttr(mapFn)
175+
};
176+
177+
expect(props.datasource.items?.map(item => props.name.get(item).value)).toEqual([
178+
"Alice",
179+
"Bob",
180+
"Chuck",
181+
"None",
182+
"None"
183+
]);
184+
});
185+
});
149186
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { ObjectItem } from "mendix";
2+
3+
export function cases<T>(...cases: Array<[ObjectItem | undefined, T]>): (item: ObjectItem) => T {
4+
const hasDefaultCase = cases.some(([obj]) => obj === undefined);
5+
if (!hasDefaultCase) {
6+
throw new Error("You must specify default case: [undefined, <your default value>]");
7+
}
8+
const map = new Map(cases);
9+
return item => {
10+
return map.get(item) ?? map.get(undefined)!;
11+
};
12+
}

packages/shared/widget-plugin-test-utils/src/main.ts

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ export * from "./builders/ListAttributeValueBuilder.js";
55
export * from "./builders/ListValueBuilder.js";
66
export * from "./builders/SelectionSingleValueBuilder.js";
77
export * from "./builders/SelectionMultiValueBuilder.js";
8+
export * from "./functions/cases.js";
89
export * from "./functions/list.js";
910
export * from "./functions/listAction.js";
1011
export * from "./functions/listAttr.js";

0 commit comments

Comments
 (0)