mirror of
https://github.com/Unleash/unleash.git
synced 2025-01-20 00:08:02 +01:00
feat: generate object combinations (#3920)
This commit is contained in:
parent
3c43dcf593
commit
3d344509a8
38
src/lib/util/generateObjectCombinations.test.ts
Normal file
38
src/lib/util/generateObjectCombinations.test.ts
Normal file
@ -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);
|
||||
});
|
29
src/lib/util/generateObjectCombinations.ts
Normal file
29
src/lib/util/generateObjectCombinations.ts
Normal file
@ -0,0 +1,29 @@
|
||||
type Dict<T> = { [K in keyof T]: string[] };
|
||||
|
||||
export const splitByComma = <T extends Record<string, string>>(
|
||||
obj: T,
|
||||
): Dict<T> =>
|
||||
Object.fromEntries(
|
||||
Object.entries(obj).map(([key, value]) => [key, value.split(',')]),
|
||||
) as Dict<T>;
|
||||
|
||||
export const generateCombinations = <T extends Record<string, string>>(
|
||||
obj: Dict<T>,
|
||||
): 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<T>[],
|
||||
) as T[];
|
||||
};
|
||||
|
||||
export const generateObjectCombinations = <T extends Record<string, string>>(
|
||||
obj: T,
|
||||
): T[] => {
|
||||
const splitObj = splitByComma(obj);
|
||||
return generateCombinations(splitObj);
|
||||
};
|
Loading…
Reference in New Issue
Block a user