{"id":302,"date":"2016-02-07T02:26:22","date_gmt":"2016-02-07T02:26:22","guid":{"rendered":"http:\/\/www.thespidercloud.com\/?p=200"},"modified":"2022-09-08T03:13:19","modified_gmt":"2022-09-08T03:13:19","slug":"breaking-down-a-function-updaterecords","status":"publish","type":"post","link":"https:\/\/frowningbear.com\/codebase\/2016\/02\/07\/breaking-down-a-function-updaterecords\/","title":{"rendered":"Breaking down a function &#8211; updateRecords()"},"content":{"rendered":"\n<p>A friend asked me to explain this code in detail for a function called <code>updateRecords()<\/code> that they were studying on an online learning site. Actually they expect you to create the guts of the function yourself and make sure it meets certain requirements. This is my solution and explanation. It is designed for somewhat beginners so Its deliberately not succinct because the purpose is to explain whats going on in detail in a simple way that is easy to follow. At the end I will demonstrate alternative ways to write the same function in a more concise manner.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Firstly here is the code without any comments.<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code lang=\"javascript\" class=\"language-javascript line-numbers\">var collection = {\n    2548: {\n      album: \"Slippery When Wet\",\n      artist: \"Bon Jovi\",\n      tracks: [ \n        \"Let It Rock\", \n        \"You Give Love a Bad Name\" \n      ]\n    },\n    2468: {\n      album: \"1999\",\n      artist: \"Prince\",\n      tracks: [ \n        \"1999\", \n        \"Little Red Corvette\" \n      ]\n    },\n    1245: {\n      artist: \"Robert Palmer\",\n      tracks: [ ]\n    },\n    5439: {\n      album: \"ABBA Gold\"\n    }\n};\n\/\/ Keep a copy of the collection for tests\nvar collectionCopy = JSON.parse(JSON.stringify(collection));\n\nfunction updateRecords(id, prop, value) {\n  var album = collection[id]; \n  if(prop === \"tracks\") { \n    if(value !== \"\") { \n      album[prop].push(value); \n\t} else if(value === \"\") {\n\t\tdelete album[prop];\t\n\t}\n  } else if(value !== \"\") { \n    album[prop] = value; \n  } else if(value === \"\") {\n    delete album[prop]; \n  }\t\n  return collection; \n}\n\/\/ Alter values below to test your code\nupdateRecords(5439, \"artist\", \"ABBA\");\n<\/code><\/pre>\n\n\n\n<p>The best way to explain any code in my opinion is to start with the most simple and gradually work up to the more complex, always remembering that greater complexity doesn&#8217;t necessarily mean harder or more advanced code, it just means more things are going on at the same time. If we break those things down one at a time we can see the code is not as hard as we might have initially thought.<\/p>\n\n\n\n<p>We have a javascript object called &#8220;collection&#8221; which itself contains 4 other objects. Each object represents an album in a music collection.<\/p>\n\n\n\n<p>Our <code>updateRecords()<\/code> function allows us to:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Update a simple string property like &#8220;album&#8221; or &#8220;artist&#8221; with a new value.<\/li><li>Add a simple property and set a value if the property doesn&#8217;t already exist.<\/li><li>Delete a simple string property like &#8220;album&#8221; or &#8220;artist&#8221;.<\/li><li>Add an item to an array if that array already exists.<\/li><li>Delete the entire array.<\/li><\/ol>\n\n\n\n<p>Lets simplify things and assume that we only want our function to be able add or update a simple string property. For the time being we wont be able to delete a property or modify the array.<\/p>\n\n\n\n<p>This is all the code we would need for our function:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code lang=\"javascript\" class=\"language-javascript line-numbers\">function updateRecords(id, prop, value) {\n  \/\/ which child object in our main \n  \/\/collection object e.g. collection[5439]\n  var album = collection[id]; \n  \n  \/\/ update an existing property or add a new property\n  \/\/ e.g. album[\"artist\"] = \"Artist Name\"\n  album[prop] = value;\n\n  \/\/ return the updated collection\n  return collection; \n}\n\n\/\/ then call the function with some arguments\n\/\/ adds an artist property to record 5439\n\/\/ and sets the value to ABBA\nupdateRecords(5439, \"artist\", \"ABBA\");<\/code><\/pre>\n\n\n\n<p>Much simpler. We can even omit the album variable and just update or add our property like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">collection[id][prop] = value;\n\n\/\/ which is the equivalent of these two lines\nvar album = collection[id]; \nalbum[prop] = value;<\/pre>\n\n\n\n<p>But lets not get carried away just yet with short-handing our code. As you can see there is not much to it. So why is the original code much longer and more complicated looking? Because we want to add the ability to delete as well as deal with an array. This requires us to build checks or tests into our code which makes it get more complex. But we can tackle that a bit at a time. For now I will keep the comments spare until the end. So here is our simple function so far without comments:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">function updateRecords(id, prop, value) {\n  var album = collection[id]; \n  album[prop] = value;\n  return collection; \n}<\/pre>\n\n\n\n<p>Now lets add the ability to delete a simple property:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">function updateRecords(id, prop, value) {\n  var album = collection[id]; \n\n  if(value !== \"\") { \/\/ if value is not an empty string\n    album[prop] = value; \/\/ add or update the value\n  } else if(value === \"\") { \/\/ but if the value is an empty string\n    delete album[prop]; \/\/ then delete that property entirely\n  }\n\n  return collection; \n}<\/pre>\n\n\n\n<p>Now before updating or adding our property we check to see if the value we supply as our argument is an empty string or not. If it is an empty string we delete the associated property completely. If the third argument is a string containing a value, we just update that property or add it if it didn&#8217;t already exist.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/ function call with a non-empty value\n\/\/ adds property \"artist\" with value \"ABBA\" or updates \"artist\" to \"ABBA\"\nupdateRecords(5439, \"artist\", \"ABBA\");\n\n\/\/ function call with an empty value\n\/\/ deletes \"arist\" property from record 5439\nupdateRecords(5439, \"artist\", \"\");<\/pre>\n\n\n\n<p>So running some checks required us to add an if else statement. Okay, but what if we want to be able to add a new song title to our tracks array? Easy just run some more checks with an <code>if<\/code> statement and a nested <code>if else<\/code> statement:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/ if statement to check if second argument supplied is \"tracks\"\nif(prop === \"tracks\") { \/\/ if yes we then run a nested if else statement\n  \n  if(value !== \"\") { \/\/ if value is not an empty string\n    \n\t\/\/ add value to \"tracks\" array\n\talbum[prop].push(value); \n  \n  } else if(value === \"\") { \/\/ if value is empty string\n    \n\tdelete album[prop];\/\/ delete  the \"tracks\" array\t\n   \n  } \/\/ close the nested if else\n\n} \/\/ close the if\n<\/pre>\n\n\n\n<p>If the argument supplied to the <code>prop<\/code> parameter is &#8220;tracks&#8221;, then we run the nested <code>if else<\/code>. Otherwise we skip all of that and move onto the next part of the code that deals with simple strings and not arrays. So our final code, with comments and spaces for readability, would look like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">function updateRecords(id, prop, value) {\n\t\n  \/\/ which child object in our main collection object \n  var album = collection[id]; \n  \n  \/\/ if we want to update the \"tracks\" property\n  if(prop === \"tracks\") { \n    \n\t\/\/ if value is not an empty string\n\tif(value !== \"\") { \n      \n\t  \/\/ add value to \"tracks\" array\n\t  album[prop].push(value); \n\t\n\t\/\/ if value is an empty string\n\t} else if(value === \"\") {\n\t\n\t  \/\/delete the \"tracks\" array\n\t  delete album[prop];\t\n\t\n\t}\n  \n  \/\/ below code is only used if updating another property besides \"tracks\" array\n  \/\/ in other words if second argument was anything but \"tracks\"\n  } else if(value !== \"\") { \/\/ if value is not an empty string\n    \n\t\/\/ add or update the value\n\talbum[prop] = value; \n  \n  \/\/ but if the value is an empty string\n  } else if(value === \"\") { \n    \n\t\/\/ then delete that property \n\tdelete album[prop]; \n  \n  }\t\n  \n  \/\/ return the updated collection\n  return collection; \n\n}<\/pre>\n\n\n\n<p>In my next update I will demonstrate how to make this code more succinct by using a bit of shorthand.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A friend asked me to explain this code in detail for a function called updateRecords() that they were studying on an online learning site. Actually they expect you to create the guts of the function yourself and make sure it meets certain requirements. This is my solution and explanation. It is designed for somewhat beginners &hellip; <a href=\"https:\/\/frowningbear.com\/codebase\/2016\/02\/07\/breaking-down-a-function-updaterecords\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Breaking down a function &#8211; updateRecords()&#8221;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3],"tags":[],"class_list":["post-302","post","type-post","status-publish","format-standard","hentry","category-javascript"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/302","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/comments?post=302"}],"version-history":[{"count":2,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/302\/revisions"}],"predecessor-version":[{"id":1376,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/302\/revisions\/1376"}],"wp:attachment":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/media?parent=302"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/categories?post=302"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/tags?post=302"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}