## FCC ‘Seek and Destroy’

This post will work through ‘Seek and Destroy’, one of freeCodeCamp‘s basic algorithm scripting challenges.  This challenge will help us introduce the Arguments object and callback functions.

The Seek and Destroy challenge states that ‘provided with an initial array (the first argument in the destroyer function), followed by one or more arguments’ we need to write a function that will remove the values of all the arguments given after the initial array, from the initial array.

Sounds confusing, I know…  Let’s visualize it to clear things up.

One of the major problems we have lies with ‘followed by one or more arguments’…  If we don’t know how many arguments there will be, how do we write a function to handle them?

The answer to that comes in the form of the Arguments object.  JavaScript provides a local variable ‘arguments’ that acts like an array with an element for each argument passed to the function.  You access the arguments just like you would an element of any other array like so:

The arguments object makes solving this algorithm challenge much easier.  Looking forward at ways to solve this problem, we need to a) access the arguments we need to delete from the initial array and b) somehow remove those arguments from the array.

Storing arguments for easy access

The first thing we’ll do is create a new array and store all the arguments (other than the initial array) in it.

As you can see, arguments can be treated like any other array…  Here, we used the length property and looped through arguments (starting at element 1 so as to avoid the initial array, which will be passed in as the first argument, or arguments).  Setting it up this way will handle any number of arguments passed to the destroyer function.

The push() method in JavaScript is used to ‘push’ new elements on to the end of the calling array.

Tools we’ll need to remove arguments from the array

In order to remove the arguments from the initial array, we will use the filter() method.  The filter method introduces a concept we haven’t talked about here at CrookedCode: the callback function.

A Quick note on functions in JavaScript

The power of functions, and what they allow you to do, are core to successful JavaScript programming.  Functions can be passed to and returned from other functions.  They can also be stored as variables.

A function that accepts another function as an argument is called a higher-order function, whereas, the function that is passed as the argument is called a callback function.  The Eloquent JavaScript chapter on functions is a great tutorial on the use of functions in JavaScript.

Eloquent JavaScript also devotes an entire chapter to higher-order functions.  I highly recommend reading and working through the examples in both of these chapters.  If you’re looking for something a little quicker, JavaScriptissexy.com has an excellent article on understanding callbacks and higher order functions.

The filter() method accepts a callback function and performs that callback on every element in the calling array.  If the callback returns true for a given element, that element is kept.  If the callback returns false, obviously, that element is not kept.

As stated above, filter() calls the callback function on every element of the calling array, but it does not mutate that array.  Therefore, you must save the kept elements as a new array.

The one final tool we’ll need before we try to solve this algorithm is the array.indexOf() method.  indexOf() will return the first index at which a given value is found.  If the given value is not found, indexOf() returns -1.

Putting it all together…. (finally)

We’ve already created argArr[] to hold the values that we need to delete from the initial array.  We now need to write a callback function for filter() that will return true if we want the element to stay and false if we want to delete that element.

We know that indexOf() will return -1 if a given value is not found.  We also know that we want to keep elements of the initial array that aren’t found in argArr[].  So, for each element of the initial array, lets call argArr.indexOf(), and return true for values of -1.  Therefore, we’ll be returning true for (and keeping) values that aren’t in argArr[].

Like so:

Wow…  This post covered a bunch of stuff we haven’t previously gone over here at CrookedCode, hopefully this helped straighten out the code for you.  See you next time…

-Jeremy

## FCC ‘Slasher Flick’

Today we’re going to work on freeCodeCamp‘s Basic Algorithm Scripting challenge – ‘Slasher Flick’.  This will be a pretty short post as we’re really not going to cover anything new,  I just wanted to go through this algorithm to show how short and concise a solution to a problem can be.

The ‘Slasher Flick’ challenge is to ‘return the remaining elements of an array after chopping off n elements from the head’.

This is the starting point FCC gives us:

As you can see, we need to write the body of the function ‘slasher’, which accepts an array ‘arr’ and a number ‘howMany’.  slasher should then return ‘arr’ with ‘howMany’ elements removed from the head, or beginning, of the array.

We can actually accomplish this challenge with just 1 line of code.  To do so, we’ll use the array.slice() method, which we first used in the ‘Title Case a Sentence’.

If you remember from that previous post, array.slice() is a method that returns a new array (which is what we need this function to return).  It takes 2 arguments.  The 1st argument is the index of where the returned array will begin, which is conveniently given to us as the argument ‘howMany’.  The 2nd argument for array.slice() is the index of the final element to include in the returned array, and is optional.  Since we’ll be returning the entire array after cutting off ‘howMany’ elements, we’ll only use 1 argument.  If you wanted to include ‘arr.length’ as the second argument to make it more clear, that would work too.

Now, given we have everything we need to return the wanted array, here’s the solution:

This function now returns the given array with ‘howMany’ elements removed from the head.

Obviously this algorithm is pretty simple, it’s part of the ‘Basic Algorithm Scripting’ after all, but I wanted to cover it to show that sometimes the solution can be pretty straightforward and simple…  No need to overthink it.

Hopefully this helped straighten out the code for you.

-Jeremy

## FCC ‘Title Case A Sentence’

Today we’re going to work through another of freeCodeCamp’s Basic Algorithm Scripting challenges – ‘Title Case A Sentence’.  To solve this challenge we must write a function that accepts a string, then returns that string with the first letter of each word capitalized and the remainder of each word in lowercase.

We’ll be using concepts that we’ve covered in previous posts (i.e. for loops, string methods, and arrays) and adding a couple new things like method chaining and some new string methods.

As I’ve mentioned previously, in JavaScript, the data type String has many methods associated with it.  W3schools has a good intro to these methods, MDN covers the string object on a deeper level.

Here’s the starting point given to us by freeCodeCamp.

We’ll start solving this challenge by breaking the given string (str) into an array of words, the same way we started ‘Find the Longest Word in a String’.

Quick tangent – we haven’t discussed yet that JavaScript can be tested right in your browser.  If you have a question about what a snippet of code does, just plug it into the console of your browser and test it.   To make sure the str.split() method that I just created is doing what I want, I plugged it into the console in Chrome and tested it.

As you can see, str.split(‘ ‘) is splitting the given string into an array, with each word as an individual element.  Now I’m confident in continuing with the solution to the algorithm challenge…

Next, we need to iterate through the array and capitalize the first letter of each word and lowercase the rest of the word.  To iterate through the array, we’ll use a for loop.  To handle the upper/lowercasing of the words, we’ll need a couple new string methods.

For a deeper understanding, and a list of many more string methods, check out the MDN page on strings.  Today, we’ll be using charAt(), toUpperCase(), toLowerCase() and slice().

toUpperCase() and toLowerCase() do exactly what they sound like, they return the calling string value in upper and lower cases respectively.  charAt() allows you to access a specific character of a string and takes one parameter – the index of the character you want to access (indexes of strings start at 0, just like arrays).

slice() allows you to access a specific segment of a string.  It takes two arguments, the indexes of where you want the segment to start and finish.  The second parameter is optional, if you leave it out, the slice will start at the first index you provide and continue to the end of the string.  Very important – all four methods mentioned above return the value of a string, they do not change the calling string.  See code below for demonstration…

Now, as mentioned above, we can chain these methods together using dot notation, so that after one method is called, a second method is called on the returned string of the first.

Check out this post on method chaining for a better understanding.

We can use everything we’ve talked about to get the first character of a string and capitalize it, then get the rest of the string (starting at index 1) and lowercase it.  Putting it all together looks like this:

Several notes on the above solution…

We used the join() method, which does the exact opposite of split.  join() is an array method that returns a string delimited by what you pass as an argument.  In this case, we gave an empty space (” “) as the argument, so each element of the array was joined together separated by a space.

Also, you will note that we used a ‘+’ to connect 2 parts of a string together.  This is an easy way in JavaScript to build a string.  It can be used with both literal strings and variables as such:

Hopefully this straightened out the code for you…  See you 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

## FCC ‘Factorialize a Number’

freeCodeCamp’s Basic Algorithm Scripting section – ‘Factorialize a Number

We’ll start digging into the freeCodeCamp (FCC) curriculum with ‘Factorialize a number’ because it’s pretty straight forward and it’ll allow us to discuss the structure of functions and introduce loops (This problem can also be solved with recursion, but we’ll get into that with some of the more complex algorithms).

The challenge is to write a function that will return the factorial of the number provided.

To understand factorials better, feel free to check out wikipedia, but basically, a factorial is the product of all integers less than or equal to n and is expressed as n!  (i.e. 4! = 4 x 3 x 2 x 1 = 24).

FCC provides the following starting point:

As I mentioned in my first post, a function is a block of code that acts independently to perform a task.  It can be called from other parts of your program, and therefore, can be used over and over to perform the same ‘function’.  Functions have many uses in JavaScript, check out Eloquent JavaScript – chapter 3 to learn more.

As you can see above, the function we’ll be building is named factorialize and has one parameter (num).  The way it’s written above, it returns that parameter (the body of a function is contained in {}).  The function is then called on line 5 and passed the argument (5).

We need to add the code that will take the parameter (num) and calculate and return the factorial of ‘num’.

We’ll start by declaring a variable to store the value of the factorial and set it equal to 1.

We’ll add the code to calculate the factorial using a while loop.  Loops allow us to set a condition, then execute a block of code until that condition is met.  MDN gives a pretty good intro to while loops here.

We’ll use the argument (num) in our condition and say:

This while loop will now iterate until num>1 is false.  Therefore, we have to remember to somehow change num each time so that eventually the loop will end (otherwise, we have an infinite loop and the program will never complete).

Now we have to do something each time the loop iterates, this is where our variable total comes in.  Given that JavaScript will execute the right side of an equation before it stores it to the left side, we can set total = total * num, then depricate num by 1.  That would look something like this:

If we walk through this for num = 5, the first pass would be

Now total = 5 and num = 4.  Since 4 > 1, the while loop will execute again.

Now total = 20 and num = 3.  This will continue until the while (num>1) fails.  It would look like this.

total = 60, num = 2.

total = 120, num = 1.

At this point, the while loop condition would be false, and the loop would end with total = 120.  Given 5! = 120, we have the right total, we just need to return it.  We can just change the return statement from return num; to return total;.

Putting everything together:

This gives us the correct answer, but JavaScript makes statements that add, subtract, multiply or divide a number by itself much easier to write using the following operators: +=, -=, *= and /=.  You can also increment and deprecate by 1 using ++ and — respectively.  See the w3schools page on operators for more info.  Knowing that, the solution seen above can be written:

These two solutions do the exact same thing and solve the ‘Factorialize a Number’ algorithm challenge.

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

-Jeremy

## Intro to JavaScript Terms

As a primer to more in depth JavaScript discussions, I figured an intro to some of the terminology that we’ll be using might be helpful.  As this will not be a complete “Intro to JavaScript” (far from it, in fact), I’ll provide links to resources that I’ve found helpful along the way.

Resources

There are several sites that I use frequently in learning to code.  Obviously, freeCodeCamp is the main one.  As I mentioned in my first post, I am currently working through the front end development certification at freeCodeCamp and highly recommend it.  While working through the freeCodeCamp curriculum I use w3schools, MDN and Stack Overflow extensively as references.  I also found that Tutorial Republic is an excellent resource for HTML, CSS and Bootstrap (which is a powerful front end framework that makes creating responsive web pages much easier).

There are also a couple books that I’ve used along the way.  The first is ‘Eloquent JavaScript‘, which is an excellent free resource (available in print also) for learning JavaScript.  It’s not exactly a book for beginners, but the online version provides examples and problems that you can work through right in the browser.  It’s the best JavaScript resource I’ve found yet…   I also picked up the Head First books ‘HTLM and CSS‘ and ‘HTML5 Programming‘.  They’re more on the beginner side, but are written well and I found them helpful in learning to interact with the DOM (which we will get into in future posts).

Intro to Terminology

Now, to cover some terms we’ll be using frequently.  In future posts, I will have to assume a basic understanding of these languages, otherwise each post will be the length of a book.  So I urge you, if you have any questions about the concepts listed below, please use the resources listed above to read more about them.

In JavaScript, groups of data are called values and these values have types.  There are 7 data types in JavaScript:

• undefined
• null
• boolean
• string
• symbol
• number
• object

Any of these data types can be stored in a variable.  To declare a variable, use the keyword ‘var’, as such:

The above statement created a variable named ‘a’.  It also includes a comment…  Anything written on a line after // is a comment and will be ignored by the browser.  You can also assign values to the variable when you create it. The following statements create variables and assign values of the various data types.

JavaScript provides several data structures called objects and arrays.  I plan on covering objects and arrays in depth in decipheredCode so for now will only cover each at a very high level.

Objects allow us to group data of various types (including other objects) as name:value pairs called properties.  Objects are used extensively in JavaScript, in fact JSON (JavaScript Object Notation) files are the way most programs pass data among themselves over the web.

An array is a list of objects or values, called elements, stored inside brackets and separated by commas.  Array elements can be accessed using bracket notation and indexes (note: first element in an array is index ).  An example of accessing the first element of an array would be:

The arr declared above would now have the string ‘apple’ as it’s first element (index ).  Chapter 4  of ‘Eloquent JavaScript’ gives a great explanation in the use of objects and arrays.

Another term used extensively in JavaScript, and programming in general, is function.  A function is a self contained block of code that can act on it’s own to do something.  A function can take a set of parameters (optional) and contains a block of code to act on those parameters.  Here’s an example of a function.

This function, named addOne, has one parameter (num).  The code inside the function creates a new variable called newNum, then sets newNum equal to num + 1 and returns the value of newNum.  The way we would use this function (or invoke it) is

This example calls the addOne function and passes the number 5 as an argument.  This function call would return the value 6.

What is an argument?  An argument is the actual value that you pass into the function, as opposed to a parameter, which is the name listed in the function definition.  I’ll be using these terms interchangeably here at decipheredCode (whether right or wrong…), so you can think of both arguments and parameters as something that gets passed into a function.

Now…  This has been a long, rambling post that mentioned a bunch of things but didn’t really explain anything in detail. I feel, however, that it was necessary before I started digging any deeper..  Hopefully, this will be helpful to someone just starting out on their journey to learn to code.  The next posts here at decipheredCode will start to dig into real problems.  Meantime, I urge anyone that is interested to check out the links that I mentioned above and to start getting their hands dirty by writing some code!

-Jeremy