Joliet
Joliet

Reputation: 101

JavaScript Short Circuit Evaluation - Missing Property Value

I'm trying to improve my coding practices so I attempted to refactor the following code:

EDIT My question is what is about the best practice for short circuit evaluation https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c

var idArray = [
    { id: 15 },
    { id: -1 },
    { id: 0 },
    { id: 3 },
    { },
    { id: null },
    { id: NaN },
    { id: 'undefined' }
  ]

let idFilteredArray0 = []

idArray.forEach(idObj  =>{
if(typeof idObj.id === 'number' && !isNaN(idObj.id))
    idFilteredArray0.push(idObj.id)
})

// from a forEach loop which returns [ 15, -1, 0, 3, 12.2 ]

let idF0 = idArray.reduce((acc, obj) => {
  if((obj.id || obj.id)  && !isNaN(obj.id))
    acc.push(obj.id)
  return acc
},[]) 

// to reduce which returns [15, -1, 3, 12.2]

I think &&'ing is the issue, but I can't see a different way to exclude the NaN value. I'd settle for getting the 0 back into the result array at this point . Lastly if anyone knows of a good source to learn short circuit evaluation, I'd greatly appreciate it. Thanks.

J.

Upvotes: 1

Views: 71

Answers (2)

Jordan Stubblefield
Jordan Stubblefield

Reputation: 523

if(obj.id) will return false when obj.id is 0. You should refactor to something like this to account for zero:

let idF0 = idArray.reduce((acc, obj) => {
  if(typeof obj.id === 'number'  && !isNaN(obj.id))
    acc.push(obj.id)
  return acc
},[]) 

And if you want to eek out some more performance, consider the following solution, which runs in linear time complexity, like .reduce(), but is much faster than the .reduce() solution:

let idF0 = [], i = 0, length = idArray.length, id;

for (; i < length; i++) {
  id = idArray[i].id;
  if (id === 'number' && !isNaN(id)) {
    idF0.push(id);
  }
}

return idF0;

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could filter and map the items and check the type and id the value is not NaN.

var idArray = [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, {}, { id: null }, { id: NaN }, { id: 'undefined' }],
    idFiltered = idArray
        .filter(({ id }) => typeof id === 'number' && !isNaN(id))
        .map(({ id }) => id);

console.log(idFiltered);

Upvotes: 1

Related Questions