1
0
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:
Mateusz Kwasniewski 2023-06-07 17:51:44 +02:00 committed by GitHub
parent 3c43dcf593
commit 3d344509a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 0 deletions

View 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);
});

View 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);
};