0

Context:

This is more of styling question in hopes of writing cleaner code.

Problem:

As shown in the code below, depending on whether certain variables hold a value or not, the code uses the variable to access deeper into the object. I have a feeling that there must be a cleaner way to go about this so I'm curious to get some inputs on this. Any insights are greatly appreciated. Thank you!

Code:

if (!stageKey) { return dataRefreshSpec?.data } if (!datasetType) { return dataRefreshSpec?.data[stageKey] } return dataRefreshSpec?.data[stageKey][datasetType] 
1
  • 1
    If you are looking to write clean code as in readable your example is good, the logic is easy to follow and dosent need commenting. If you are going by linecount (which is never something you need to strive for) slappys answer will do. Both uses the same number of comparisons. Yours is clearer to read than his. Commented Apr 24, 2020 at 19:45

1 Answer 1

1

I might first test for the existence of the full path, and then access it. If it isn't there, then you know you can only go so far as the stageKey if it exists, otherwise just the .data.

if (stageKey && datasetType) { return dataRefreshSpec?.data[stageKey][datasetType] } return stageKey ? dataRefreshSpec?.data[stageKey] : dataRefreshSpec?.data 

Or like this, if I got the new syntax right:

return dataRefreshSpec?.data?.[stageKey]?.[datasetType] ?? dataRefreshSpec?.data?.[stageKey] ?? dataRefreshSpec?.data 

Or there's this old standby, which will probably work, depending on your requirements:

return (((dataRefreshSpec || {}).data || {})[stageKey] || {})[datasetType] 

These last two are technically a little different, since they don't test the value of they key itself, but rather its result when applying its value to the objects.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.