I have a JavaScript function to categorize data by their "styles" attribute, and store the key-"unicode" pair.
Here's my current code:
function processMetadata(metadata) {
let regular = {}, solid = {}, brands = {}
for (let icon in metadata) {
let styles = metadata[icon].styles
let codePoint = metadata[icon].unicode
if (styles.includes('regular')) {
regular[icon] = codePoint
}
if (styles.includes('solid')) {
solid[icon] = codePoint
}
if (styles.includes('brands')) {
brands[icon] = codePoint
}
}
return {regular, solid, brands}
}
However, CodeClimate keeps complaining about
Function
processMetadata
has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring.
I want to resolve this issue, but I'm not aware of any way to further reduce the complexity without reducing the performance of this code. The following snippet does reduce the cognitive complexity to under 5 but at the expense of performance (3+3 loops instead of 1) and extra dependency:
function processMetadata(metadata) {
let regular = _.pickBy(metadata, icon => icon.styles.includes('regular'))
regular = _.mapValues(regular, icon => icon.unicode)
let solid = _.pickBy(metadata, icon => icon.styles.includes('solid'))
solid = _.mapValues(solid, icon => icon.unicode)
let brands = _.pickBy(metadata, icon => icon.styles.includes('brands'))
brands = _.mapValues(brands, icon => icon.unicode)
return {regular, solid, brands}
}
Is there any way I can achieve this without having a significant impact on the performance?