Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript array or object checking – code improvements

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
  }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading