Record collection challenge question

Not sure if i should have created a brand new post for this but it was in teh same vein so I figured it would be more appropriate in this same post:

So In reference to the ‘record collection’ challenge that precedes The object properties challenges, I had already coded it using similar code as this ‘profile look up’ challenge where I put two conditions into the very first clause. but After revisiting the challenge with this knowledge that you have given me here in this forum I have re-structured it using the type of logic structure you have show me here. I have restructured it using the top-down style like you guys are mentioning earlier, whether for better parsing or just structure of logic in general. Code works for both versions, and the logic from he second version works as well. Can you take a look at both versions and give me your feedback please? @JeremyLT

v1

function updateRecords(id, prop, value) {

  if(prop !== "tracks" && value !== ""){
     collection[id][prop] = value
  }

  if(prop === "tracks" && collection[id].hasOwnProperty("tracks") === false){
    collection[id].tracks = []
  }

  if(prop === "tracks" && value !== ""){
    collection[id][prop].push(value)
  }

  if(value === ""){
    delete collection[id][prop]
  }

  
  return collection;
}

v2:

function updateRecords(id, prop, value) {

  if (prop !== "tracks") {
    if (value !== "") {
      collection[id][prop] = value
    }

  }

  if (prop === "tracks") {
    if (!collection[id].hasOwnProperty("tracks")) {
      collection[id].tracks = []
    }
    if (value !== "") {
      collection[id].tracks.push(value)
    }
  }

  if (value === "") {
    delete collection[id][prop]
  }

  return collection;
}

I think you can reduce a bit more considering this:

  • the behaviour for value === "" is universal, it doesn’t depend on the prop value, you can avoid checking for value !== "" if you do first the thing for value === ""

  • prop === "tracks" and prop !== "tracks" are mutually exclusive, you could put one of the two as an else statement

  • in this case that you have a series of conditions for which only one should happen, an if/else if/else chain is ideal

1 Like