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
CodePudding user response:
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) {
props.forEach((item) => conversionValues.push(getResult(item)))
} else {
conversionValues.push(getResult(props));
}
return conversionValues;
}
}
CodePudding user response:
In fact, you can force all data
into a one-dimensional array and safe work with array of objects only.
Is this code sexy enough?
const obj = {id: 1, val: 1};
const arr = [{id: 1, val: 1},{id: 2, val: 2},{id: 3, val: 3}];
const normalize = (data) => [data].flat();
console.log(normalize(obj)[0]);
console.log(normalize(arr)[0]);
// -------------------
// and you can use this approach in code:
const getResult = (obj) => obj.val * 10;
const CalculateIt = (props) => [props].flat().map(getResult);
console.log(CalculateIt(obj));
console.log(CalculateIt(arr));
.as-console-wrapper{min-height: 100%!important; top: 0}