I receive data => these data could be array of object or just a object.
I write some code, but maybe there is a way to make this code more sexy, clear, or shorter plus without any errors
Here is the code:
export const CalculateIt = (props) => {
const conversionValues = []
if (props) {
if (props.length > 0) {
for (let i = 0; i < props.length; i++) {
const clicks = props[i]?.insights?.[0].inline_link_clicks
const actionsNumber = props[i]?.insights?.[0]?.actions?.length || 0
let result = 0
if (clicks && actionsNumber) {
result = devideNumbers(clicks, actionsNumber, 8)
}
conversionValues.push(result)
}
return conversionValues
}
const clicks = props?.insights?.[0].inline_link_clicks
const actionsNumber = props?.insights?.[0]?.actions?.length || 0
let result = 0
if (clicks && actionsNumber) {
result = devideNumbers(clicks, actionsNumber)
}
return conversionValues.push(result)
}
}
As you can see there you can find some parts of the code that are similar like:
const clicks = props[i]?.insights?.[0].inline_link_clicks
and
const clicks = props?.insights?.[0].inline_link_clicks
Is it possible to write it more smart?
Best
>Solution :
Probably move the common code in a function:
function getResult(data) {
const clicks = data?.insights?.[0].inline_link_clicks
const actionsNumber = data?.insights?.[0]?.actions?.length || 0
let result = 0
if (clicks && actionsNumber) {
result = devideNumbers(clicks, actionsNumber, 8)
}
return result;
}
And use the helper function in your original function:
export const CalculateIt = (props) => {
const conversionValues = []
if (props) {
if (props.constructor === Array) {
for (let i = 0; i < props.length; i++) {
conversionValues.push(getResult(props[i]))
}
} else {
conversionValues.push(getResult(props));
}
return conversionValues;
}
}