FCC Advanced Algorithm Scripting Challenge – ‘Map the Debris’

Today we’ll work through our first Free Code Camp advanced algorithm challenge called ‘Map the Debris‘, which will give us some exposure to working with objects.

This challenge asks us to ‘Return a new array that transforms the element’s average altitude into their orbital periods’

It further tells us that the array will contain objects in the following format:

FCC also points us to this wikipedia page to read about orbital periods.

Finally, it gives us the following as a starting point:

I think, given the limited amount that we’ve spent on objects here at crookedCode, we should start with a brief overview.

I’m not going to reinvent the wheel and write thousands of words on JavaScript objects when so many others have covered it much better than I ever could.

I will, however, point you to, and urge you to read, chapter 4 and chapter 6 of Eloquent JavaScript.  This will take some time, especially if you work through the examples (which I highly recommend) but you’ll have a much greater understanding of objects once you’re done.

Some basics about JavaScript Objects:

Here, I’ll cover objects in enough detail to get us through this FCC algorithm.  If you’ve read the chapters mentioned above, this should all be review.

In JavaScript, objects are basically a collection of properties that can be wrapped together and stored in one variable. Properties consist of {key: value} pairs.

I think the best way to demonstrate this concept is through an example.  I don’t know why, but let’s say I wanted to create myself as an object…  It might look something like this:

This example shows 4 sets of key: value pairs, the first of which is – firstName: ‘Jeremy’ – with firstName being the ‘key’ and ‘Jeremy’ the ‘value’.  All 4 of these properties are now stored under the variable – me.

I can access and manipulate the properties through dot notation (bracket notation can also be used, but we’re going to stick with dot notation throughout this exercise).

In the example below I will access my age and change it to 21 (I know, I know, wishful thinking….).

As you can see when I logged the ‘me’ object to the console, the age has now been changed from 41 to 21.

We’ve seen object properties above as strings or numbers, but they can really be any data type, including other objects or functions.  When a property in an object is a function, it is said to be a ‘method’ of that function.  I’ll demonstrate how we can add new properties to objects below by giving ‘me’ a hair color property and a method.

Ok, suffice to say, this is only scratching the surface with objects in JavaScript, but I think we can move on to solving ‘Map the Debris’.

Before going any further I feel I should say there are many ways to solve this problem…  Some of them, I’m sure, are much more ‘slick’ than mine. This is the solution, however, that I wrote and am providing here as a working solution in an attempt to help anyone who is struggling or looking for a different perspective.

Solving ‘Map the Debris’

We know from the problem description that we will be getting an array of objects as an argument, and that each object in this array will have name and avgAlt properties.

We need to take each of the avgAlt properties, calculate the orbital periods (based on the equation given to us on the Wikipedia page referenced above), and return an array of objects that contain name and orbitalPeriod properties.

First things first, how do we calculate an orbital period?  Below is the formula given on Wikipedia.

orbperiod for crookedcode

This equation might look a little intimidating if it’s been a while since your last math class, but we have all the elements we need.  We just have to rewrite the equation in JavaScript and fill in the correct values.

Fortunately, there’s a Math object in JavaScript that has all the methods associated with it that we’ll need (i.e. pi=Math.PI, squareroot=Math.sqrt(), exponents=Math.pow(base,exponent).  We’ll also use Math.round() to round our answer to the nearest whole number as required by the challenge.

My logic for setting up the solution was as follows:

  • Write a function that solved the orbital period given the avgAlt (let’s call the function findOrbPeriod)
  • Then write a loop to cycle through the array of objects that
    • adds an orbitalPeriod property with a value calculated using the findOrbPeriod function.
    • deletes the avgAlt property for each object in the array.
  • Return the array.

If you’re working through Free Code Camp, I would suggest taking what we just talked about and try to solve the equation on your own.

Otherwise, proceed on…

Spoilers_ahead

Let’s start by writing the function that will solve the orbital period.

As you can see, we use the avgAlt plus the earth’s radius for ‘axis’ in the equation.  The second line in the function is the orbital period equation listed above, only written using the JavaScript Math object.  Finally, we return the orbital period so we can use this function to populate the new orbitalPeriod property of each object.

Now we can tie everything together by cycling through the array of objects (arr) and calling the function we just wrote (findOrbPeriod()) for each object.

As you can see, the for loop adds an orbitalPeriod property to and removes the avgAlt property from each object in arr.  Then all we have to do is return arr.

There we go!!  We made it through our first  FCC advanced algorithm.  Hopefully this helped straighten out the code for you, feel free to leave any questions or comments below.  Until next time…

-Jeremy

FCC ‘Find the Longest Word in a String’

The next freeCodeCamp algorithm that we’ll work on here at The Crooked Code will be ‘Find the Longest Word in a String’.  The challenge here is to write a function that accepts a string as a parameter and returns the length of the longest word in the string, which means we’ll be returning a number.

Before we start on the algorithm, there are a few JavaScript concepts that we’ll need to go over…

In JavaScript, methods are functions that are stored as object properties. Further, there are many methods that are built into JavaScript that are available to manipulate things like strings and arrays.  This algorithm will let us start exploring the methods associated with these various data types.  This concept might not seem immediately clear, however, this w3schools page explains the concept in a little more detail, or just keep reading this post and things should clear up.

As is the case with accessing other properties of objects, we can use dot notation to call these methods.

Let’s try to clear things up with an example:

String.split() is one of many methods that can be used on a string.  Split() will divide a string into an array of substrings.  It takes up to two arguments.  The first argument is the separator, or where the string will be divided.  The second argument is the limit and is optional.  The limit is a number specifying the max number of substrings (we won’t be using this second argument is this example).  In use, split() looks something like this:

A few things to note in this code…  We passed (‘ ‘) to str.split which means str will be divided into substrings at each whitespace.  (if you pass (”) str will be split at every letter, if you pass ‘,’ it’ll be split at every comma and so on..).    Also, console.log() is an excellent way of checking that your code is doing what you want.  In this case, we passed it the array of strings (arrOfStr) in which we stored all the substrings so we could check if the code was doing what we intended.  As you can see from the line below the console.log call, arrOfStr now contains 4 different strings, 1 for each word in the original string (str).

One more quick thing to cover before we get into solving the algorithm – arrays.  An array is a data structure that allows us to store a list of multiple values in a single variable.  Each value in the list is called an element and can be accessed individually using bracket notation, which is also explained in this MDN page.  An example using bracket notation with the above example would be:

As you can see, the index (the number inside the bracket notation that accesses an individual element in the array) of the first element of an array is 0.  Therefore, when we log index 0 of arrOfStr to the console we get ‘this’.  A good intro to arrays can be found here.

Ok, now moving onto the problem at hand…

FCC provides the following starting point:

We need to write the code inside the findLongestWord function that will return the length of the longest word.  FCC then starts to check your code by calling findLongestWord with the string ‘The quick brown fox jumped over the lazy dog’.

We can start by splitting the original string into an array of individual words as such:

We also need to create a variable to store the value representing the length of the longest word.

Now we need to write a loop to go through wordArray and look for the longest word.  Something to help with both these tasks is the method .length which can be used on both strings and arrays.  String.length will return the number of characters in a string.  Array.length will return the number of elements in an array.

A for loop is an easy way to iterate through an array.  The for loop is different from the while loop used in the last algorithm in that it is initiated using three statements.  A decent intro to a for loop can be found here but I’ll try to use an example to illustrate how it works:

The first statement (var i = 0;) executes before the loop begins.  In this case, we initialize a variable (i) to equal 0.  The second statement (i < 5) is the condition that must remain true for the loop to continue.  In this case, the loop will iterate 5 times (while i is equal to 0 through 4).  The third statement is executed at the end of each iteration, in this case, i is incremented by 1 each time.

Combining everything we’ve discussed thus far to solve the algorithm:

The comments in the code ( everything following //) should help you follow the logic.  The only thing in the code that we didn’t cover previously is the if statement.  The code is fairly self explanatory, but you can read up on if statements on this MDN page.   Basically, if the statement inside the () of an if statement is true, the code following (either a single line or a block inside {}) is executed.  In this function, the if statement is used to check if the current word is longer than the previous longest word.  If true, the length of the new longest word is stored in wordLength.

Hopefully this straightened out the code for you.  See you next time.

-Jeremy