Optimizing generics file

This commit is contained in:
2023-11-26 13:35:40 +01:00
parent d717fc8410
commit c56d6b1688

View File

@ -1,3 +1,7 @@
export function objectWithArraysToArrayOfObjects(
input: Record<string, any>,
arraysToArrays: string[]
): Record<string, any>[] {
/*
* Transforms object with arrays into array of objects
*
@ -6,10 +10,6 @@
* @returns {Record<string, any>[]} Array of objects
*
*/
export function objectWithArraysToArrayOfObjects(
input: Record<string, any>,
arraysToArrays: string[],
): Record<string, any>[] {
const inputCopy = { ...input };
arraysToArrays.forEach((k) => {
if (Array.isArray(inputCopy[k]) && !Array.isArray(inputCopy[k][0])) {
@ -24,7 +24,7 @@ export function objectWithArraysToArrayOfObjects(
acc.keys.push(key);
return acc;
},
{ keys: [] as string[], maxLength: 0 },
{ keys: [] as string[], maxLength: 0 }
);
const output: Record<string, any>[] = [];
@ -42,6 +42,10 @@ export function objectWithArraysToArrayOfObjects(
return output;
}
export function arrayOfObjectsToObjectWithArrays<T extends Record<string, any>>(
array: T[],
mergeObject: Record<string, any> = {}
): Record<string, any> {
/*
* Transforms array of objects into object with arrays
*
@ -50,12 +54,7 @@ export function objectWithArraysToArrayOfObjects(
* @returns {object} Merged object with arrays
*
*/
export function arrayOfObjectsToObjectWithArrays<T extends Record<string, any>>(
array: T[],
mergeObject: Record<string, any> = {},
): Record<string, any> {
return array.reduce(
(acc, obj) => {
return array.reduce((acc, obj) => {
const mergedObj = { ...obj, ...mergeObject };
Object.keys(mergedObj).forEach((key) => {
if (!acc[key]) {
@ -64,11 +63,13 @@ export function arrayOfObjectsToObjectWithArrays<T extends Record<string, any>>(
acc[key].push(mergedObj[key]);
});
return acc;
},
{} as Record<string, any>,
);
}, {} as Record<string, any>);
}
export function filterObject(
obj: Record<string, any>,
filter: string[]
): Record<string, any> {
/*
* Filter certain keys from object
*
@ -77,11 +78,7 @@ export function arrayOfObjectsToObjectWithArrays<T extends Record<string, any>>(
* @returns {object} Filtered object
*
*/
export function filterObject(
obj: Record<string, any>,
filter: string[],
): Record<string, any> {
return Object.fromEntries(
Object.entries(obj).filter(([key]) => filter.includes(key)),
Object.entries(obj).filter(([key]) => filter.includes(key))
);
}