Spaces:
Build error
Build error
File size: 1,319 Bytes
d9494a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import { trimAndRemoveDuplicatedWhitespacesFromString } from '@/utils/trim-and-remove-duplicated-whitespaces-from-string';
export const extractAndSanitizeObjectStringFields = <
T extends object,
TKeys extends (keyof T)[],
>(
obj: T,
keys: TKeys,
maxDepth = 10,
): {
[P in TKeys[number]]: T[P];
} => {
const processValue = (value: unknown, currentDepth: number): unknown => {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
if (currentDepth >= maxDepth) {
return value;
}
if (Array.isArray(value)) {
return value.map((item) => processValue(item, currentDepth));
}
if (typeof value === 'object') {
const obj = value as Record<string, unknown>;
const objKeys = Object.keys(obj);
return objKeys.reduce(
(acc, key) => ({
...acc,
[key]: processValue(obj[key], currentDepth + 1),
}),
{},
);
}
if (typeof value === 'string') {
return trimAndRemoveDuplicatedWhitespacesFromString(value);
}
return value;
};
return keys.reduce((acc, key) => {
const value = processValue(obj[key], 0);
if (value === undefined) {
return acc;
}
return {
...acc,
[key]: value,
};
}, {} as T);
};
|