diff --git a/src/lib/util/generateObjectCombinations.test.ts b/src/lib/util/generateObjectCombinations.test.ts new file mode 100644 index 0000000000..81cd72a122 --- /dev/null +++ b/src/lib/util/generateObjectCombinations.test.ts @@ -0,0 +1,38 @@ +import { generateObjectCombinations } from './generateObjectCombinations'; + +test('should generate all combinations correctly', () => { + const obj = { + sessionId: '1,2', + appName: 'a,b,c', + channels: 'internet', + }; + + const expectedCombinations = [ + { sessionId: '1', appName: 'a', channels: 'internet' }, + { sessionId: '1', appName: 'b', channels: 'internet' }, + { sessionId: '1', appName: 'c', channels: 'internet' }, + { sessionId: '2', appName: 'a', channels: 'internet' }, + { sessionId: '2', appName: 'b', channels: 'internet' }, + { sessionId: '2', appName: 'c', channels: 'internet' }, + ]; + + const actualCombinations = generateObjectCombinations(obj); + + expect(actualCombinations).toEqual(expectedCombinations); +}); + +test('should generate all combinations correctly when only one combination', () => { + const obj = { + sessionId: '1', + appName: 'a', + channels: 'internet', + }; + + const expectedCombinations = [ + { sessionId: '1', appName: 'a', channels: 'internet' }, + ]; + + const actualCombinations = generateObjectCombinations(obj); + + expect(actualCombinations).toEqual(expectedCombinations); +}); diff --git a/src/lib/util/generateObjectCombinations.ts b/src/lib/util/generateObjectCombinations.ts new file mode 100644 index 0000000000..19fba40a54 --- /dev/null +++ b/src/lib/util/generateObjectCombinations.ts @@ -0,0 +1,29 @@ +type Dict = { [K in keyof T]: string[] }; + +export const splitByComma = >( + obj: T, +): Dict => + Object.fromEntries( + Object.entries(obj).map(([key, value]) => [key, value.split(',')]), + ) as Dict; + +export const generateCombinations = >( + obj: Dict, +): T[] => { + const keys = Object.keys(obj) as (keyof T)[]; + + return keys.reduce( + (results, key) => + results.flatMap((result) => + obj[key].map((value) => ({ ...result, [key]: value })), + ), + [{}] as Partial[], + ) as T[]; +}; + +export const generateObjectCombinations = >( + obj: T, +): T[] => { + const splitObj = splitByComma(obj); + return generateCombinations(splitObj); +};