I'm facing a challenge with a function that has a cognitive complexity of 24, however, we have a requirement to limit it to a maximum of 15.
export function parameterValueParser<T extends Structure>(
structure: T
): (parameterValue: Value) => Parsed<T> | null {
return (parameterValue: Value): Parsed<T> | null => {
if (isParameterValueNumber(structure)) {
return parseNumber(parameterValue) as Parsed<T> | null;
}
if (isParameterValueStruct(structure)) {
const parameterValueChildren = parseStruct(parameterValue);
if (parameterValueChildren == null) {
return null;
}
const result = {} as { [_: string]: Parsed<Structure> };
for (const key in structure) {
if (structure.hasOwnProperty(key)) {
const child = parameterValueChildren[key];
if (child == null) {
return null;
}
const parsedChild = parameterValueParser(structure[key])(child);
if (parsedChild == null) {
return null;
}
result[key] = parsedChild;
}
}
return result as Parsed<T>;
}
return null;
};
}
The cognitive complexity is mainly due to the nested if statements, especially those under a for..of loop. Even extracting the code into a separate function may not significantly reduce the complexity. Any suggestions on how to effectively reduce its complexity?