Issues with "Record Collection" challenge

Issues with "Record Collection" challenge
0.0 0

#1

**

WARNING! Don’t read further if you haven’t solved this yet!

**


Not all the tests are performed for checking if the solution is correct.

Missing Test:-
If value is non-blank (value !== “”) and prop is not “tracks” then update or set the value for the prop.

Test if an existing property is correctly changed (e.g. updateRecords(5439, “album”, “Test”) )

This should change the original from

5439: {
  album: "ABBA Gold"
}

to

5439: {
  album: "Test"
} 

I found this problem to be exceedingly difficult partly due to the hazy/incomplete way it has been described. (I spent over 2 hours figuring out what is asked of us and coding the solution):slight_smile:

I also had to use stuff we have not yet learned (typeof and checking for undefined properties).

Hence, I am questioning if what I have done is correct.

This is my solution :-

// Only change code below this line
function updateRecords(id, prop, value) {
  // Add a new record
  if (typeof collection[id] == "undefined") {
    var newObj = {};
    if (value !== "") {
      newObj[prop] = value;
    }
    collection[id] = newObj;   // In ES6, we can use:- collection[id]={[prop]:value}; insted of creating a new object first
    return collection;
  }
  // Add a new property to an existing record
  if (typeof collection[id][prop] == "undefined" && value !== "") {
    if (prop === "tracks") {
      collection[id][prop] = [value];
    }
    else {
      collection[id][prop] = value;
    }
    return collection;
  }
  // Update a property of an existing record
  if (value !== "") {
    if (prop === "tracks") {
      (collection[id][prop]).push(value);
    }
    else {
      collection[id][prop] = value;
    }
  }
  // Delete a property from an existing record
  else {
    delete collection[id][prop];    
  }
  return collection;
}

Any thoughts on this from other “FreeCodeCampers” would be appreciated.

Thanks,

  • Jay

#2

This looks fine to me, and it passes all the tests. If you want to make the code a bit cleaner, you can omit the typeof operators and the equality checks for value as they’re practically redundant in JavaScript.

if (typeof collection[id][prop] == "undefined" && value !== "")

…could be

if (!collection[id][prop] && value)

They’re not the exact same statements if you break down the logic, but at least in this project, they’re functionally the same. This is possible because JavaScript considers both the type undefined and an empty string to be logically false, meaning you can just test for existence in these cases.


#3

Thank you PortableStick

Learned something new about javascript.