Tag: bonfire



Bonfire: Where Do I Belong Solution

where do I belong

I was getting excited months ago when Where Do I Belong was the last of the foreseeable Beginner’s Bonfires we’d be doing. But it looks like there’s one more after this so let’s see what Free Code Camp has for us this time:

function where(arr, num) {
  // Find my place in this sorted array.
  return num;
}

where([40, 60], 50);

Looks like our Bonfire wants us to locate and return the lowest number where num should be placed. So, for example, if we had an array like [3, 5, 8, 12, 17] and we wanted this Bonfire to run and spit out where the number 10 would belong, it would return 2 because 8 is the lowest number that is less than 10 and it is in the second position in our array. The Bonfire gives us a clue about using sort(). Let’s start there.

Approaching the Problem

  • Sort is actually one of the first things we need to do to the array so we can organize the numbers in the off-chance the Bonfire gives us a list of numbers that isn’t chronological. So sort() is called pretty much immediately upon entering the function.
  • We’re going to need to determine which number is larger than num and for that, we’ll have to loop through our array to find that number.
  • Once we know what the number is, we’ll have to return its place in the array as the answer.

Sorting Through Sort()

Sort() is a method used on arrays to arrange the values in order. The order imposed by sort() is a bit hairy so you’ll have to be careful when using it. Sort() can take in a function that you may wish to write in order to specify the sorting and comparison process. If you don’t supply sort() with a function, it will do its best. Very often, though, this involves sort() converting your number values (if any) into strings.

In terms of sorting order, here’s what sort() interprets when you don’t feed a compare function into it…

  1. Numbers
  2. Uppercase Characters
  3. Lowercase Characters

So, let’s put this into action. Here’s an array sorted using sort():

var myArray = ["4 Badgers", "five goats", 3, 19, "Elephant"];
console.log(myArray.sort());

Here’s the output: [ 19, 3, “4 Badgers”, “Elephant”, “five goats” ]

You’re going to find something pretty obviously wrong with the outputted array. Why is 19 supposedly greater than 3? Because sort() is looking only at the first character in the string. So it’s really only seeing this: 1, 2, 4, E, f. What you’ll need to do in order to get your numbers to sort accurately is include a compare function like this:

var myArray = [41, 892, 6, 29, 7, 88];
myArray.sort( function(a,b) {
return a - b;
});
console.log(myArray);

And the output: [ 6, 7, 29, 41, 88, 892 ]

Fantastic, our numbers are being sorted accurately now. Interesting thing to note is if you want descending instead of ascending order, here’s how you’d get sort to work that out:

var myArray = [90, 4, 12, 998, 57, 16];
myArray.sort( function(a,b) {
return b - a;
});
console.log(myArray);

And you should get: [ 998, 90, 57, 16, 12, 4 ]

Pretty nifty! Though if you tried to run that through with the array earlier where we mixed and matched numbers and strings, the order of the strings are still messed up. In order to get a fully accurate sort, we would have to work with regex and that would veer off into a direction that is far beyond what this Bonfire is asking us to do. So, let’s get back to the Where Do I Belong Bonfire now that we understand how sort() is working.

Sorting Out Where Do I Belong

Here’s what I’m working with first. We know that we need to sort an array with numbers inside of it and just to keep things simple, I’m going to sort the array in ascending order (going from smallest to largest). Here’s what I’m getting:

function where(arr, num) {
arr.sort( function(a, b) {
 return a - b;
 });
return num;
 }

where([40, 60], 50);

Nothing fancy going on yet that we haven’t already encountered and we’re putting sort to good use. We can now assume that whatever numbers are in our array will now be sorted in ascending order. Our next order of business is to loop through that array and compare the numbers to num to locate the one in line that’s less than or equal to num. There’s a bit of a catch here because whatever we get, we’re going to have to convert it into an int to return a valid answer for our Bonfire. This is where parseInt() comes into play. It’s detour time.

A Little Detour into parseInt()

parseInt() is a method, often used when working with sort() because the latter will tend to convert your numbers into strings so it can work with them better. All things about passing Bonfires aside, putting out a string that’s a number is much sloppier than just putting out a straight up number. Especially given our task at hand here where we should clearly be putting a number through the validation and not a string. So that’s where parseInt() comes into play with our Where Do I Belong Bonfire.

parseInt() takes in strings and returns an integer (or number). It takes in two parameters, a string and a radix. If you ask me what a radix is, you will get to see a fantastic deer in the headlights look. If I were to explain it as simply as I can, a radix is a base numbering system or how many numbers are in an ordering system. Probably the most recognizable radix out there is the base 10 system. Which we should all be familiar with because it looks like this:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Another numbering system you might be familiar with is Base 16, which is also known as hexadecimal. So, before this throbbing headache of mine gets worse, let’s put parseInt() into action so we can see how it works:

console.log(parseInt("19, 897, 56", 10));

And the output: 19

console.log(parseInt("math scares me", 10));

The output: NaN

parseInt(), in a really simplified nutshell is returning the first character it encounters. So if it’s not a number, it returns as a NaN. If it is a number, it determines the radix you want and returns the number accordingly. Interestingly enough, your second parameter (or your radix) can be a number from 2 to 36. Now that we’ve had this brief visit into the terrifying workings of parseInt(), let’s get back to our Bonfire.

The Where Do I Belong Solution

With that having been said, here’s our solution…

function where(arr, num) {
arr.sort( function(a, b) {
 return a - b;
 });
for (var i = 0; i <= arr.length; i++) {
 if (arr[i] >= num) return parseInt(i);
 }
 return arr.length;
 }

where([40, 60], 50);

After sorting our array, I created a for loop that checks all the values inside of the arr array. As it loops through each value it checks to see if that particular value is greater than or equal to num. If it is, the loop exits and returns the position of that number in the form of an integer, which is where parseInt() comes into play. Plug it into the Bonfire and you’ll get a pass.

Resources

Javascript Kit, Sorting a Javascript Array
Great explanation with really easy to understand examples of sort().

MDN, parseInt()
MDN’s page on parseInt(), a method that my fingers keep trying to type as praseInt().

StackOverflow, How Do I Convert a String Into an Integer
A super helpful question and answer and briefly covers the use of parseInt().



Bonfire: Seek and Destroy Solution

Seek and Destroy

Two more Bonfires (unless Free Code Camp wants to add more) after Seek and Destroy! I’m a little excited to be finished with these so we can move onto some more complicated challenges. Nothing so far about these Bonfires has been particularly challenging and they’ve been a great reminder as to what Javascript can accomplish–on a more development-focused scale. So let’s see what we can do about Seek and Destroy. Here’s what the Bonfire gives us:

function destroyer(arr) {
  // Remove all the values
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

We need to remove the arguments from the array provided to the destroyer() function. We can see in the arguments that it probably wants us to remove all 2s and all 3s. If we’ve already survived the previous Bonfires, then this one will be pretty easy.

Approaching the Problem

  1. I know that I need to remove all 2s and 3s from the array, but I can pretty much guarantee that the Bonfire won’t just be filtering out static 2s and static 3s. It’s going to change things up on us, and the best way for us to come up with a surefire way to get everything is to turn the two arguments into an array themselves.
  2. Remember when we talked about indexOf() in the Mutations Bonfire? We’ll be using it again here to help us identify where in the array of numbers we need to be in order to remove those values.
  3. Finally, I’m going to need to use filter() to remove the argument values from the array in order to validate my Bonfire.

All right, we have our game plan, so let’s get started.

Changing Arguments Into an Array

The first thing I’m going to approach is the easiest and, incidentally, the first thing on my to do list. I always like to start off with the easiest thing because it’s less intimidating than trying to tackle the hardest task first. So, what I’m going to do is turn the two arguments into an array. We’ve done something like this in the past, only we were using strings then. This is going to be an array of numbers now, so here’s what I’m doing:

function destroyer(arr) {
var myArguments = [];
for (var i = 1; i < arguments.length; i++) {
myArguments.push(arguments[i]);
}

  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

What I’ve done up there is create an empty array called myArguments. That array will take the arguments from the destroyer() function so that we can use whatever values Bonfire throws at us. The catch is, we don’t know what those arguments are going to be. So we use the arguments object to identify those values and push them to our myArguments array. Looks like we’re going to have to take a brief detour.

The Arguments Object

The arguments object exists in Javascript to present the arguments that are passed into a function. This is useful for our purposes because it retrieves whatever we input as the index number. For example, let’s take our destroyer() function from this bonfire. If you were to return arguments[1], you would receive the number 2 as a result. Go ahead:

function destroyer(arr) {
return arguments[1];
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Let’s try something that’s a little easier to visualize. Here’s another function, this time there are strings instead of numbers so we know for sure what arguments is useful for:

function cats(arr) {
return arguments[2];
}

cats("Bengal", "Scottish Fold",["Persian", "Russian Blue", "Moggy"], "Abyssinian");

Plug that into a console and it will return the array. You can go ahead and play with arguments a bit more by changing the number, but whatever the number you plug in will correspond to the arguments fed into the cats() function. One of the caveats of the arguments object is that it exists only within a function. So you can’t use it all willy-nilly outside or you’ll encounter an error.

Now, my next move in this Seek and Destroy solution is to use filter() and if I’m remember things correctly, we haven’t encountered that method yet. So let’s dive in.

The Filter() Method

Filter() is a Javascript method that creates a new array based upon a function that was fed to it. That function must return a value in order for filter() to create an array. This is a particularly useful method because we’re essentially going to use it to test for the values inside our new myArguments array, and if those values happen to exist in myArguments, they will fail the filter() test and not be included in the array we’re going to build. Filter() looks for a true or a false value. True gets added to the array, false does not. Here’s an example of filter() in action:

function isLess(number) {
 return number <= 10;
 }

var filtered = [4, 87, 11, 9, 19, 789].filter(isLess);
 console.log(filtered);

The console log on that one should be 4, 9. What’s happening up there is filter is taking in a function. The function is called isLess and is defined with an argument of number. Number returns whatever is less than or equal to 10. Which in our array is just two of the six numbers: 4 and 9.

Now that we know what filter() is expecting, let’s go solve this Seek and Destroy challenge.

Seek and Destroy Solution

Knowing that I can use the arguments object to my advantage, I now have two arrays. One that I’m given by the Bonfire to filter numbers out of. Another one that holds all the two (or more) arguments that I want to filter out. All we need to do now is write the filtering code and return arr.

function destroyer(arr) {
// Create an array of arguments using the arguments object
var myArguments = [];
for (var i = 1; i < arguments.length; i++) {
myArguments.push(arguments[i]);
}
// Return arr after filtering values in myArguments
return arr.filter( function(remove) {
  return myArguments.indexOf(remove) < 0;
});
 }

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

We’re seeing a return of our old friend, indexOf() in the above solution. Let’s walk through this Seek and Destroy solution from top to bottom now. destroyer() the function has three arguments. The first is an array, the next two are numbers. Our challenge was to filter out the two arguments from the provided array in destoyer().

What we do first is create an array callled myArguments. myArguments uses the arguments object to iterate through all the arguments provided in destroyer. The for loop starts at 1, which is the second value in the array (2). You may have noticed we don’t start at 0 like usual because we don’t want our for loop to populate the array itself into our new myArguments array. Once the for loop finishes, myArguments should contain all the arguments the Bonfire wants us to use in order to exclude from the array.

After we have our myArguments array set up, we must return arr with the excluded values. What we do is use the filter() method. Filter() takes in a function that is used to exclude whatever values myArguments is holding. Inside of our filter() method, we have a function that takes in another argument called remove. In the function itself, remove identifies each value of myArguments using indexOf() and returns them to remove for filter() to use.

Remove sends the values we evaluated up the chain and back to the filter() method, which determines that all values remove returned must be filtered out of arr. Then we return arr with a new array, devoid of the values inside of myArguments. Plug that into the Bonfire and it will evaluate.

Resources

MDN, Filter()
Describes the filter() method and shows some examples of its usage.

MDN, Arguments Object
Explains the arguments object and how it works. Very quick and easy read.



Bonfire: Falsy Bouncer Solution

Falsy Bouncer

Having checked the Bonfires recently to this post for the Falsy Bouncer Bonfire, I discovered Free Code Camp has included a new Bonfire for the Beginner’s Algorithm Scripting challenges. I haven’t looked at it yet, but it sounds intriguing as a Caesar’s Cipher involves moving letters a certain number of spaces and can appear in a number of skill tests. Anyway, we’re dealing with the Falsy Bouncer in this post, so here’s what the Bonfire gives us to work with:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  return arr;
}

bouncer([7, "ate", "", false, 9]);

Bonfire wants us to remove all the false values in the array. Within Javascript’s lexicon, false is equivalent to: false, NaN, undefined, 0, null and “”. Given what we have above, I’m assuming they want us to exclude “” and the false value so that 7 will eat 9. Let’s get this show on the road.

Approaching the Problem

  1. I already know in Javascript what it considers as a false value already, so I need a way for an if statement to exclude those values before returning the array in bouncer() without them.
  2. The Bonfire gives us a hint about what we can use by suggesting we look into the filter() method.
  3. If we just filter out the false values, we can easily return the non-false values in the array and validate our solution.

It would seem that our path is pretty clear cut on this one. So let’s dive into it and look at what filter() does.

Looking at Filter()

Filter is a method added to ECMAScript (Javascript) 5. It allows Javascript to arrays to test values in an array for true and returns a new array by filtering out those values that didn’t pass the test. It’s a handy new feature and I can understand why the Falsy Bouncer Bonfire can be solved in this way.

The crazy thing about filter() is that it takes in a function and an object as arguments. So a typical filter() method’s syntax looks like this: filter(callback[, thisArg]). Callback is the function that you use to test the values in an array, element or index. thisArg is an object you may or may not use as a form of this, it is considered optional.

That might sound like a lot of Martian up there so here’s an example of filter() in use, where we invoke filter() to weed out and return only the strings in an array:

var mishMash = [4, "cookies", true, "cake", 18, "peppermints", 0];

var isTreat = mishMash.filter(
    function (treat) {
        return (typeof treat === "string");
    }
);
console.log(isTreat);

In the above section of code, we first create an array called mishMash. Inside of mishMash, we have a mixture of values. Some numbers, some strings and a true boolean value. What I want to do is create another array that contains only strings.

What we create on the next line is a new array called isTreat. isTreat is populated using the filter() method on mishMash. Inside filter() we feed it a function that takes in a property of “treat”. treat, inside of the function, is tested to see if it is a string or not. If it is a string, it gets returned. Once treat gets returned it is added to isTreat as a value of the array. And finally, we log out isTreat which should tell us that its array’s values are “cookies, cake, peppermints”.

Here’s another example, where we check for true values inside of an array. By default, in Javascript, true is any value that isn’t false. So, as long as it doesn’t return as false, 0, null, NaN, undefined or an empty string, it will return in our array:

var lies = ["cake", 5, true, 0, 1, true, "", false];

var nothingBut = lies.filter(
    function (theTruth) {
        return theTruth;
    }
);
console.log(nothingBut);

In the above code, we’re looking for, theTruth, or any value that isn’t false which means the array should exclude 0, “” and false. What we do is start a new array called nothingBut. We feed nothingBut the lies array, using the filter() method. Filter takes in a function that checks for true, it refers to true as theTruth.

Remember that the filter() method tests values in an array, element or index for true by default, so we don’t have to do anything for filter except have it return the values to the new nothingBut array. The result when you log it out is “cake”, 5, true, 1, true. Therefore, successfully excluded all false values and only gave us the truth, and nothing but the truth.

Chatting Briefly About typeof

You probably noticed typeof being used up there as a way to evaluate whether something is a string or not. I feel like it’s necessary to mention typeof because I haven’t used it before and therefore, haven’t explained myself yet. So in the interest of being thorough, let’s take a brief look at typeof.

Typeof is a Javascript operator. It’s used to evaluate and return the type of something. As you can see above, typeof is very useful for evaluating if something is a string. You can also evaluate for numbers, nulls, undefines, booleans, objects, functions and more.

A typical use of typeof:

var cats = "felines";
console.log(typeof cats);

The above should log, “string”, because, well that’s what the variable cats is holding onto. Here’s another example:

var sharks = ["hammerhead", "mako", "great white"];
console.log(typeof sharks);

The above should log, “object”, which is true because an array is a type of object in Javascript. You can get more specific if you need to determine an array from another type of object by using the Array.isArray() method, but let’s not open that can of worms right now. Finally, a really simple last example:

var cake = false;
console.log(typeof cake);

The above logs a “boolean”. Now we know how typeof is used and you also know how much I love the Portal games.

Knowing how to filter out true values and being acquainted with typeof, we can now apply filter() to figure out our Falsy Bouncer Bonfire challenge.

The Falsy Bouncer Solution

So, filter() checks for true values. Seeing as we’re 99% of the way there in our filter() example above, let’s just apply the same thing to our Bonfire to get our solution:

function bouncer(arr) {
    var truths = arr.filter(function(filterTrue) {
        return filterTrue;
    });
    return truths;
}

bouncer([7, "ate", "", false, 9]);

In the code above, we declare the bouncer() function with an array as an argument (arr). Inside of that function, we create a new array called truths. This array will hold only the true values returned by the filter() method. The new truths array is declared to have values of arr which are put through the filter() method. Filter() checks for and tests all array values for true and returns these values in the form of the filterTrue argument.
Finally, when all the values in the array are checked and the false ones are excluded by filter(), we return truths to bouncer() and get all our truths and none of the falses. Run this one through the Bonfire and it will validate! Looks like we just solved our Falsy Bouncer challenge.

Resources

Dive Into Javascript, Array Filter Page
A useful page describing filter() and how it’s used, including a bunch of examples for its usage.

MDN, Filter()
MDN’s explanation and examples for the filter() method.

MDN, Typeof
MDN’s page on the typeof operator, includes examples and explanations.



Bonfire: Mutations Solution

Mutations

I’m getting excited because after this Mutations Bonfire, there will only be three left to go through before we hit the Intermediate Bonfire challenges! Free Code Camp has also been growing and adding to their learning map and we might be seeing some more coding challenges coming out of it. For now, though, let’s get over Mutations and see where these Beginner’s Bonfires take us next.

Here’s what the Bonfire starts us off with:

function mutation(arr) {
  return arr;
}

mutation(["hello", "hey"]);

No message of encouragement? That’s OK, the Bonfire wants us to test the two strings fed into mutation() to see if they contain the same letters regardless of what order the letters are in (for example, “orange” and “range” should return true, whereas “puppy” and “carton” would return false). Bonfire wants us to test the letters only, so we should assume that if there were capitals letters involved in one string but not in the other, it should still return true (for example, “Olive” and “olive” should still return true).

There’s going to be a little bit more code put into this one than the Slasher Flick Bonfire, so let’s get on with it by doing an approach.

Approaching the Problem

  1. Like we’ve seen in Bonfires past, whenever we have to deal with comparing one string to another where title or lower case doesn’t matter, we should endeavor to strip the strings of capitals as one of the first steps.
  2. What we’re going to need to do after stripping the strings of uppercase characters is compare them in some way. An if statement nested inside of a for loop will allow us to test all the characters and evaluate for truth or falsehood. We can use indexOf() and charAt() to accomplish this. If I remember right, prior to Free Code Camp switching to their own Javascript lessons, we dealt briefly with indexOf() and charAt() with Code Academy.

Setting Up For the Mutations Solution

The first thing I’m going to do, like I stated in my approach is force the strings to become lowercase to take that variable out of the equation and make evaluating the two strings much easier. We do that by using the toLowerCase() method. We’ve seen toLowerCase() before in the Title Case a Sentence Solution and the Check for Palindromes Solution. It essentially takes in a string and forces all characters to become lowercase. Fairly straightforward. We’re going to call toLowerCase() here and apply it to both of the arrays that mutation() took in as arguments.

function mutation(arr) {
var firstString = arr[0].toLowerCase();
 var secondString = arr[1].toLowerCase();
return arr;
}
mutation(["hello", "hey"]);

In the above code, I’ve taken the first value in arr and the second value in arr and forced them both to be lowercase using toLowerCase(). Since mutation() was feeding us an array with two values in it, I had to reference arr, plus whichever array position contained the value I needed to manipulate. This should give us two lowercase strings to work with.

Next up, we’re going to need to write a for loop that will iterate through the first or second string and compare it to the other. So let’s write that now:

function mutation(arr) {
var firstString = arr[0].toLowerCase();
 var secondString = arr[1].toLowerCase();
for (var i = 0; i < secondString.length; i++) {
}
return arr;
}
mutation(["hello", "hey"]);

In the above code, I’ve added a simple for loop that will iterate through all the characters (or the total length) of secondString. Inside of this for loop, we’re going to run an if statement using indexOf() and charAt() to compare the characters of firstString to secondString and see if they match up. The reason why we’re running the for loop on secondString is so we can evaluate true for instances where firstString might have a value of “alien” and secondString might have a value of “line”. If we wrote the for loop for firstString, it will evaluate to determine if “line” has all the characters of “alien” instead of the other way around. This will cause Bonfire to reject your solution, so use secondString to loop and check firstString against.

Let’s Talk indexOf()

Before we get to the solution from here, let’s take a brief journey down the magical path of array methods. Most notably the two we’re going to use to evaluate firstString and secondString. Let’s start with indexOf().

indexOf() is an array method that’s used to return a number that specifies the place of the first instance of a string within an array. I know how sloppily put together that sentence is so here’s an example that should demonstrate how indexOf() works a little more clearly:

var endWorld = "What the caterpillar calls the end of the world the master calls a butterfly.";
 var word = endWorld.indexOf("master");
console.log(word);

In the above code, you should log out the number 52, which is the start of the word “master”. It should be noted that both indexOf() and charAt() consider spaces as a part of the index of a string, and in case you haven’t guessed by now, 0 is the first position.

So, we’ll use this method in our solution on firstString to tell it to go through each of the characters in its array and evaluate it against secondString. Another very useful thing about indexOf() is you don’t need to search full words, you can search partial words or single characters. Like this:

var love = "Love is metaphysical gravity.";
 var letter = love.indexOf("t");
console.log(letter);

The above should return 10 for the first t that appears in ‘metaphysical’. Now, indexOf() can also return a -1. When it does that, it means that there was a hiccup somewhere, or indexOf() simply didn’t find a match for what was searched. Let’s take a look at charAt() now.

Taking a Look at charAt()

charAt() is a little similar to indexOf(), except instead of returning the number where a character or string occurs, it returns the character when we feed it a number. Here’s an example of charAt() in action:

var words = "A thousand words will not leave so deep an impression as one deed.";
var deeds = words.charAt(11);
console.log(deeds);

The above will log out ‘w’ because that’s the character at position or index value 11. charAt() is going to be useful for us as we use it to return a character at a specific number while looping through and checking secondString against firstString.

The Mutations Solution

OK, now that we have those two methods down. Let’s work out our solution. The first thing we need to do is ensure that we can check firstString using an if statement and iterate through all of its characters. We’re going to use indexOf() and feed it the value of i, because i is what we’re using to loop through secondString. This ensures that we work through the entirety of firstString and check each and every character in it:

function mutation(arr) {
var firstString = arr[0].toLowerCase();
var secondString = arr[1].toLowerCase();
for (var i = 0; i < secondString.length; i++) {
if (firstString.indexOf(i) == -1) {
return false;
}
}
return true;
}
mutation (["hello", "hey"]);

What we’re building up there is a framework for checking firstString. I’ve got a placeholder variable of i in the indexOf() right now, so if you ran this, it won’t evaluate properly in the Bonfire and will likely return false. But what we’re doing is putting firstString through an if statement. We’re evaluating each of its characters as we iterate through firstString using the variable i, which is set to the length of secondString. We have an equals to operator that checks to see if at any point indexOf() returns -1, if it does then false is sent to mutation(), if indexOf() never returns -1, then true is sent to mutation(). Let’s finish this now by adding in the check for charAt() with secondString:

function mutation(arr) {
var firstString = arr[0].toLowerCase();
var secondString = arr[1].toLowerCase();
for (var i = 0; i < secondString.length; i++) {
if (firstString.indexOf(secondString.charAt(i)) == -1) {
return false;
}
}
return true;
}
mutation (["hello", "hey"]);

And there we have it. What we added was secondString.charAt(i) which iterates through secondString’s characters using i which is set to secondString’s length. If at anypoint indexOf() returns a -1 (which means it can’t find a character in secondString that equals a character in firstString, we get false. If it never gets -1, we return true. Run it and it will evaluate. Yay! We solved the Mutation problem.

It’s been a while since I’ve had to dig this deeply into any kind of code, and I have nothing even remotely close to a formal education in Computer Science Theory, but my impression of mutations in programming was that it has to do with changing something to something else during runtime. As a side effect of this, mutation also deals with the concept of the order in which operations are done as very often in your code, you might be looking back at what something used to be before it was “mutated”.

The fact that this Bonfire is called Mutations makes me think they’re trying to get something across about how this order of operations business is going to go down. And if I’m not mistaken, this isn’t really the first time we’ve dealt with mutations, it’s only the first time the Bonfires called it for what it is. If you want to read up more about mutations, there’s an excellent paper here about it. Not specifically geared toward Javascript, but still useful regardless of what programming language you’re dealing with.

Resources

MDN, charAt()
A description of charAt(), what it does and a ton of examples about how to use it.

MDN, indexOf()
A page about indexOf() on the MDN. Describes what it does and includes lots of examples.

Wulkan.me Mutations Solution
Wulkan has a different approach to the solution for this Bonfire. His solution trims out the usage of charAt().



Bonfire: Slasher Flick Solution

Slasher Flick

Today we’re going to look into the Bonfire Slasher Flick. The good news, and there’s only good news for this one, is that the solution is extremely simple. The best news is, the solution here isn’t anything we haven’t seen before. So while the title might be a little intimidating, the exercise is pretty straightforward.

Let’s dive into the Slasher Flick by seeing what Free Code Camp has thrown at us today:

function slasher(arr, howMany) {
  // it doesn't always pay to be first
  return arr;
}

slasher([1, 2, 3], 2);

So we have the slasher() function that takes in two arguments: arr which is an array of numbers and howMany which is a number that we are supposed to trim from the array. The Bonfire has already given us a couple of good hints, by telling us we might want to look into using the slice() or splice() methods. You might recognize splice() from our previously solved Chunky Monkey Bonfire Solution. And going back a little further, slice() was used and explained in our Title Case a Sentence Bonfire Solution. Essentially, either will work for what we’re going for here. Let’s get started then.

Approaching the Problem

  1. I need to trim or “slash” the numbers from a provided array based upon whatever number appears in the second argument of the slasher() function. In this case, I know I need to take in the array itself into the function as an argument and then how many numbers I have to trim as another argument.
  2. arr, in this case is the array. Right now the Bonfire is returning the straight up array, when we need to use howMany as a basis for trimming that many values from arr.
  3. If I use slice, I can reference howMany and use it on arr. Then return it to get my solution.

How, we’ve already talked slice() and splice() into the ground. If you need a refresher on how they work, go ahead and check out my linked solutions above. Both will walk you through how each of the two methods are used. I’m going to pick the easier of the two to work with and send slice() in to do the heavy lifting for this solution.

The Slasher Flick Solution

The first thing I’m going to do is use slice() with an argument of howMany. This tells slice() where to go to get the number for how much it’s supposed to, well, slice. Next thing I need to do is call slice on my array. The Bonfire has already gotten us 90% of the way there, and all that’s really left for us to do is call slice(howMany) in the right place. This results in:

function slasher(arr, howMany) {
  return arr.slice(howMany);
}

slasher([1, 2, 3], 2);

In the above code, I am adding a call to slice(howMany) to the return of arr. This means that when we head into slasher(), we’re going to take arr, then return it while slicing off whatever value is in howMany. Run that thing through the Bonfire and it will validate.

Using Splice() Also Works

If you want to be a non-conformist, or just be a little different about this, the splice() method will work in essentially the same way. You also write it in pretty much the same way except instead of calling slice(), you call splice() instead:

function slasher(arr, howMany) {
  return arr.splice(howMany);
}

slasher([1, 2, 3], 2);

That will validate just as easily as the slice() solution. Hooray! It was about time we got an easy one. I hope you all have a great New Year. See you in 2016!

Resources

MDN, Slice()
A useful page that explains what slice() is and how it works on arrays.

MDN, Splice()
A useful page that explains how splice() works on arrays and what it is.



Bonfire: Chunky Monkey Solution

chunky monkey

Ah, the Chunky Monkey. I’ve been, ever so gratefully, swamped with work (hooray!) But this Bonfire Solution has been a long time coming. I’ve been eyeing this one since I saw the name of it so let’s take a look at it. Unfortunately, it has very little to do with the Ben & Jerry’s ice cream flavor and a whole lot to do with Javascript arrays.

Here’s what Free Code Camp has provided us in this Bonfire:

function chunk(arr, size) {
  // Break it up.
  return arr;
}

chunk(["a", "b", "c", "d"], 2);

FCC wants us to split the array and group them into a multidimensional array based upon the size argument in the chunk() function call. Let’s get started.

Approaching the Problem

  1. First thing’s first, if I’m not already crystal clear on it, I’m going to have to define what a multidimensional array is and how JS makes things confusing and probably start an empty one to fill in later with my return values.
  2. I’ll have to approach the array splitting in one of two ways. I can use split() or I can use splice(). Whichever one I end up with, it’s going to have to be approached in the form of a loop and be based on whatever number falls into that second function argument.

The Different Flavors of Arrays

Arrays come in different types, and in various programming languages you might see support for more array types or less. Now, we’ve been working with arrays a lot with these Bonfires, and in this one FCC wants us to create a multidimensional array. I don’t spend days pondering the intricacies of JS arrays, so I might not have the most definitive answers for you. You can check out the MDN page on arrays for more information. For the rest of us just learning, here’s a simple rundown:

Associative Arrays – Are arrays that use strings instead of numbers to act as a “key” in the key value pair. For example:

// create an empty array called myCar.
var myCar = [ ];
// populate the myCar array with key value pairs.
myCar['color'] = 'red';
myCar['type'] = 'sedan';
myCar['make'] = 'Honda';
myCar['year'] = 2010;

In the above code, we created an associative array called myCar. Then we go on to populate it with values using keys to identify them. For example in the declaration: myCar[‘color’] = ‘red’, ‘color’ is considered the key and ‘red’ is the value. So when you need to reference the value red, you would use the key to call it up:

console.log (myCar['color']);

Seeing an associative array at work, it’s hard not to see how similar in function it is to a regular old object. Which is why some programmers recommend that instead of using JS’ associative arrays which can be confusing and aren’t seen all that often, you just create an object instead. It’s easier to understand, and you can do more with it and more efficiently. Here’s the same thing as what you saw above, except we use objects instead:

// create an object using object literal notation and call it myCar then populate it with properties.
var myCar = {
color : 'red',
type : 'sedan',
make : 'Honda',
year : 2010
}

And to get at the color for the myCar object, you would also use the key to call it up:

console.log (myCar['color']);

So that’s Associative Arrays, long story short, objects are easier and faster to work with. But what about Multidimensional Arrays?

Multidimensional Arrays – Are arrays within arrays. So technically, a multidimensional array can hold other arrays inside of itself. For example:

var myDesserts = [
['carrot cake', 'chocolate cake', 'cheesecake'],
['apple pie', 'pumpkin pie', 'plum pie'],
['shortbread cookies', 'chocolate chip cookies', 'sugar cookies']
];

In the above code, we’ve created an array called myDesserts. Within the myDesserts array, it contains three elements. Each of those elements is an array that contains three values each. So if I wanted to access ‘plum pie’ in the above code, I’d have to call it up like this:

console.log (myDesserts[1][2]);

In the above code, I’m referencing the myDesserts multidimensional array, then telling it to go into the second array (we reference the number 1 to find the second array because JS starts counting at 0) and then give me the third value in that second array (we reference 2 to get the third value because 0 is ‘apple pie’ since JS starts counting at 0), which should be plum pie.

So now that we know what these two kinds of arrays are, let’s get back to our Bonfire, which is actually considerably simpler than all this talk about arrays.

Building the Solution with a While Loop

I’m going to use a While Loop for this chunky monkey challenge, but a For Loop will work just as well–it’s only a little more verbose and not really necessary. First thing I’m going to do is create my empty While Loop and my empty multidimensional array to push my values into:

function chunk (arr, size) {
var chunked = [];
while () {
}
return chunked;
}

The above code is just a skeleton of what I’m planning to do. But I’ve declared an empty array called chunked. Then set up an empty while loop that doesn’t do anything useful yet. And finally, I’m returning the chunked array. All stuff we should be really familiar with by now. Next thing I’m going to do is evaluate the length of arr. So that it will essentially run the loop and take care of all the values that arr might have fed into the function. This is what that will look like:

function chunk (arr, size) {
var chunked = [];
while (arr.length) {
}
return chunked;
}

Finally, I’m going to use a bunch of methods to perform two major things. I want to add values into an array where each array contains two values within it. This means we need a and b in one array and c and d in another, both of those arrays will have to go into my chunked array. What I’m going to use is a method called splice(). Hold onto your hats, we’re heading into another sidetrack.

The Splice() Method

Splice() is a handy method in Javascript that allows you to remove elements from an array and, if it pleases you, add elements back in. It can even return the removed elements. It has a couple of efficiency boosts over split() because with one splice(), you can both add, remove and return. Here’s splice() in action:

var myJams = ['Cranberry', 'Strawberry', 'Grape', 'Apple'];
myJams.splice(1, 3, 'Crabapple', 'Orange');

console.log(myJams);

In the above code, I declared an array called myJams, which originally contains four types of jams: Cranberry, Strawberry, Grape  and Apple. On the next line, I use the splice() method to select the start and end of where I want to do my splicing (start at position 1, end at position 3) and I designated two new values to add to the array: Crabapple and Orange.

The result when logged out will be: Cranberry, Crabapple, Orange. What splice did was remove the old values in myJams starting at position 1 (Strawberry) and ending on position 3 (Apple). Then it put Crabapple and Orange at the end of myJams. The two numbers in the arguments will give you the range of splicing, then what comes after is what you want to add in. So, I could very well have something like this instead:

var myJams = ['Cranberry', 'Strawberry', 'Grape', 'Apple'];
myJams.splice(1, 2, 'Crabapple', 'Orange', 'Plum', 'Banana', 'Pomegranate');

console.log(myJams);

And the log would reveal this list for myJams: Cranberry, Crabapple, Orange, Plum, Banana, Pomegranate, Apple. This is because I started at 1, but ended at 2 and pushed the remaining values into the place left open from where I removed those values. Therefore, instead of seeing the new values added at the end, they get placed into the middle spaces where the old values used to be.

Using splice, we can trim away the values from the array we don’t need and replace it with the values declared as the arr argument.

Solving the Chunky Monkey Challenge

Here’s the solution:

function chunk (arr, size) {

var chunked = [];
while (arr.length) {
chunked.push(arr.splice(0, size));
}

return chunked;
}

chunk(["a", "b", "c", "d"], 2);

We’ve already gone through the easy stuff, so let’s focus on the magic inside of the while loop. We’re checking to make sure that we loop through all values within the arr argument. So for each of those values, we go in and push to the chunked array each value in arr. For each of the arr values, we want to splice them. We start splicing at 0 and splice it using the value for size (which is 2 in this case). So each time we run through the splice, it knows that we want it all spliced, and to split things up into groups of two. This works well enough if you want groups of 3, 4, 5, etc. So long as you have the values and an appropriate size argument for each. Even if you don’t have enough values to feed into the function, it would still group as many as it can into groups and push the rest into an array. Give it a try with ten values, then push them into groups of 4 to see how it works. In the mean time, we’ve solved Free Code Camp’s Chunky Monkey Bonfire.

I had to do a lot of looking up and experimentation to get at the solution for this one, so check out some of the Resources I referenced for additional help and information.

Resources

Microsoft DN, Splice Method
For some reason, I found Microsoft DN’s explanation of splice() to be the easiest to understand so here it is.

MDN, Splice Method
Another resource for splice(), more detailed this time.

SharkySoft, Multidimensional Arrays Explanation
SharkySoft’s ultra-minimalist approach to design and development has put this particular page in a warm place within my heart. It’s also a great explanation of JS Multidimensional Arrays.



Bonfire: Repeat a String Solution

This time on the FreeCodeCamp Bonfire experience network, we’re going to Repeat a String by however many times have been fed into the properties of the function repeat(). Here’s what FreeCodeCamp has given us:

function repeat(str, num) {
  // repeat after me
  return str;
}

repeat('abc', 3);

We also have one upfront caveat to consider: if the number fed into repeat’s second property is a negative number, we must return an empty string. Funny enough, this is one of the easier Bonfires in my opinion to work with because you don’t really need to know any new methods. Let’s get started.

Mapping Out the Problem

  1. I know I’m going to end up using a loop for this, so the trick to determine which kind of loop is the most appropriate for this situation.
  2. I need to weed out negative values while I’m at it and should probably do that in the loop, or to make things more efficient, weed out negative values before anything gets looped. That way, we’re not constantly checking for negatives while we count down.
  3. I see FCC is planning to check the string for invalidate characters too. Fantastic, we’ll have to weed those out as well.
  4. Strings are constants/immutable, whatever. I’ll need to create a variable to hold the string that gets outputted as a result.

Using the Repeat() Approach

This is pretty straightforward if you choose to use the repeat() method like the Bonfire suggests. What you need to do first is ensure that the function doesn’t run for any negative values. That means you have to check to make sure num is greater than 0. If num is less than 0, then we need it to return an empty string. You can do that with a return and empty quotes:

function repeat (str, num) {

if(num > 0) {
      return str;
    } else {
      return '';
    }
}

repeat('abc', 3);

The above code will return the string, but it doesn’t repeat it. We need to use the repeat() method for that. And since repeat() is a new thing, let’s take a look at it first.

A Foray Into Repeat()

Repeat() is a useful method in Javascript that takes a string and–you guessed it–repeats it however many times you indicate in the method’s parameters. It is typically used like this:

myStr.repeat(4);

Where whatever myStr is, you will see it repeated 4 times. Repeat(), handily enough, doesn’t take negative values all too well, and will round up floating point numbers to integers. This makes it the perfect candidate for our Bonfire solution. Here’s the finalized approach:

function repeat (str, num) {

if(num > 0) {
      return str.repeat(num);
    } else {
      return '';
    }
}

repeat('abc', 3);

Validates and passes you onto the next Bonfire. But we aren’t really done yet. What if you don’t want to use the repeat() method? We’ve actually already learned how to deal with situations where we have to repeat a string before. Possibly even in some of those JS lessons we took before we got to the Bonfires. Wouldn’t a simple loop perform the same thing that we just did using repeat()? Yep.

The For Loop Approach

This is a case where a For Loop or any other kind of loop would resolve the problem. Here’s my approach with a For Loop.

function repeat (str, num) {
  var wordStr = '';
  for (var i = num; i > 0; i--) {
    wordStr += str;
  }

return wordStr;
}

repeat('abc', 3);

In the above code, I declare an empty variable called wordStr. This is going to be used to add the strings to it however many times specified by repeat()’s properties. Then I go into the For Loop. The loop identifies i as whatever num is. It then checks to make sure i (num) is greater than 0. Then decrements i (num) accordingly. If i is greater than 0, it concatenates whatever str is onto our wordStr variable. Then outside of the For Loop, wordStr, and all of the strings that were repeated, are returned for evaluation.

The While Loop Alternative

I had said before that any loop could do this job. I have a particular affinity with the For Loop, but a While Loop is just as valid. Even a Do While Loop will evaluate for this Bonfire, but it really isn’t recommended to use a Do While for this.

Using a While Loop, though, is perfectly good. Here’s a While Loop solution:

function repeat (str, num) {
  var wordStr = '';
  while ( num > 0) {
    wordStr += str;
    num--;
  }

return wordStr;
}

repeat('abc', 3);

A Really Inefficient Use for the Do While Loop

And while (I’m corny) we’re here, a Do While Loop is possible, but I’ve found that I needed to check for negative values before it even goes into the Do While Loop, where the negative value is checked again. This would, of course, invalidate this as a solution because though it works, it’s so far beyond inefficient, it’s not even worth mentioning. A Do While Loop is really only useful if we had to run the function through at least once before we evaluate it. This isn’t the case here with this Bonfire, but I would have felt bad leaving Do While out. Here it is in case anyone was curious:

function repeat (str, num) {
  var wordStr = '';
  
  if (num > 0) {
  do {
    wordStr += str;
    num--;
  } while ( num > 0);
    }

return wordStr;
}

repeat('abc', 3);

And there we have it, we’ve repeated a string for our Bonfire using a For Loop and a While Loop. And I even wrote out the world’s most inefficient Do While Loop while I was at it.

Resources

MDN, String.prototype.repeat()
One of the easier to read MDNs explaining repeat() in detail.



Bonfire: Confirm the Ending Solution

Bonfire wants us to confirm the ending of a string so that whatever is last in a string matches whatever value we put into as another variable. Here’s what it starts us off with:

function end(str, target) {

 return str;
 }
end('Bastian', 'n');

Knowing Free Code Camp, they’re not going to make it as easy as us evaluating the last character in a string. I’m sure they’ll evaluate whatever solution we come up with in more robust terms. Perhaps using our solution against entire words or even sentences. This is one of those frustratingly easy to solve human exercises that tests how we condense a simple process into a logical series of steps. Let’s get started with an approach.

Approaching the Problem

  1. I know that I probably need to analyze more than just one character in a single word string. Doing just that would be pretty simple, but by now, we should know that FCC never wants the most obvious answer because they’ll continually check against more complicated scenarios. So, I’m going to head this off now by making sure I dynamically check whatever the last characters are in whatever they throw at me.
  2. Next thing I need is something to process the string I’m checking (the string we are checking for the last thing). The Bonfire gives us a clue that we should be looking at substrings which we encountered very briefly in Finding the Longest Word. Just a quick recap, substring is a method that allows us to split a string up based upon a couple of parameters that we designate. One of those parameters allows us to designate the end of a string by using a negative number or negative value.
  3. We’ll need to evaluate if the original value we’re checking against is the same as the value we saved in our variable. If it is, we’ll return a true value and that’ll be that.

Setting Up The Framework

This is one of those scenarios where showing something might just be simpler than describing it. So let’s get started. As usual, I’ll get the easiest stuff out of the way. Let’s declare our conditional framework.

function end (str, target) {
if ( ) {
 return true;
 } else {
 return false;
 }
 }
end('Bastian', 'n');

A Brief and Glorious Return to SubStrings

Now that we have that out of the way, we’ll have to determine what exactly we’re doing with substring. Substring is written as substr(). It takes two values. The first value determines where in the string we want to start sectioning things up. The second value tells us the length of the substrings we want. For example, if I had something like this:

var str = "My favorite treat is banana pie!";
var mySubString = (str.substr(3, 8));
console.log (mySubString);

The console would log out, “favorite” because it’s starting on the third character (the f) and it’s selecting the next eight characters (favorite). Now, I mentioned before that substr can take negative values. Using a negative value with the substr() method will allow you to start or select from the end of a string rather than at the beginning. For example:

var str = "I'm a fan of cabbage rolls.";
var mySubString = (str.substr(-6));
console.log (mySubString);

The console will log out, “rolls.” with the period because you’re telling substr() to select the last six characters in the string. This is handy for us because we can use it to:

a) Find the last components of the original string (str).
b) Dynamically check the last component with itself (target).

Let’s get back to our Bonfire.

Checking for the Ending

There isn’t a whole lot we need to do with this one because the framework conditional we set up above was honestly the majority of the work. The most complicated part of this Bonfire is next, that’s the bad news. The good news is, once we get that out of the way, we’re done. Here’s the finalized solution:

function end(str, target) {
  if (str.substr(-target.length) == target) {
    return true;
  } else {
    return false;
  }
}

end("Bastian", "n");

What we did inside of that conditional statement is first we determined the last characters of whatever target is. Target pulls its information from the second parameter fed into the end() function. In this case, target is “n”. If we were calling the function as end(“Bastian”, “ian”), then target would be “ian”.

So, knowing that target is already holding what we have to evaluate, we use it with a negative value declared in the substr() method coupled with .length to determine what str is. In this case, str would be “n”. Now that we’ve populated str, we check it against regular old target, which is also “n” and if they’re equal, we return true. If they’re not equal, we return false.

Here’s a visual run down of what’s happening with a different set of parameters for end():

Let’s say we have the following function call:
end(“The Unicorn Ranch”, “Ranch”);

Inside of our actual function, we’re taking in two parameters str and target. Like this:
function end (str, target)

We know str = The Unicorn Ranch, and target is Ranch according to the end() call. Next, we know we have to get to the last values of str, and determine if those are the same as target. Since we already know what target is, we’ll use it to evaluate against str. We can do that by using substr() to select the last elements of str. And the last elements of str will be identified by checking target (Ranch) based upon its length:
str.substr(-target.length)

The above chunk of code is essentially saying, “start from the end of str, then use however long target is to select that many characters.”

Finally, once we have that information, we check it against plain old target, which allows us to evaluate if the last values of str are the same as target. Plug in the above code chunk and you should evaluate and pass the Bonfire.

Resources

Gorka Hernandez
Continues to be a great resource with excellent alternative solutions.

Wulkan.me
Has an alternative solution that is a little more verbose, but might be easier to read for some.

MDN, Substr()
A good place to read up on the intricacies of substr(). And while you’re there, check out substring() and sub().



Bonfire: Return the Largest Numbers in an Array Solution

Let’s take a look at today’s Bonfire challenge, returning the largest numbers in an array. I was a bit thrown by this one, honestly, because something about numbers just intimidates me. So let’s approach this one slowly. First of all, here’s what Free Code Camp gives us:

function largestOfFour(arr) {
 // You can do this!
 return arr;
 }
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");

We can do this.

Approaching the Problem

Well, first thing, what we have isn’t a simple array where we can just do a single simple for loop and return the largest number for one array. We have to deal with all four arrays and return the largest among the numbers in each of the four arrays.

So my original plan to use a simple for loop is going on the backburner. The best/worst part about about these Bonfires is that they never test your solution on a straightforward case so that you have to think about your situation a bit more.

So here’s my thought process.

  1. I need an empty array to hold the largest of each array so I have something to return, and I need a variable to hold the largest number from each array too. So that’s one empty array I’m creating, and one empty variable.
  2. What I want to do is loop through the arrays inside of the largestOfFour arrays so I’ll need one for loop to go through largestOfFour then loop through each of the four arrays within.
  3. I then need to write another for loop that goes through each of the numbers inside of each of the four arrays. So I’m going down two levels of loops because we have arrays inside of largestOfFour array.
  4. I need to compare or sort the numbers inside of the array of numbers and determine the largest one. The largest one should be sent to the empty variable and then pushed to the empty array I created in step 1.

It seems a little convoluted to me, but the only ideas I had involved for loops, and looping while inside of a loop. I was sure there were other options out there, and I did find some to lead me to my eventual solution for this Bonfire.

Finding the Largest Numbers With For Loops

I kind of had to take it slow with this one because 1) numbers intimidate me, and 2) Loops inside of other loops to deal with arrays inside of other arrays make me frustrated because it can get so messy. And the most succinct alternate solution I found made me wish I’d thought of it first. Wulkan.me has it posted: here.

OK, without further ado, the first thing I did was the easiest possible thing. Small steps:

function largestOfFour(arr) {
var largestNumberArray = [];
var highestNumber = 0;
}

I defined an empty array to hold my largest numbers, and a variable to hold my highest number from each of the four arrays in largestOfFour. Now that the easy part is done, I’m going to write my first for loop:

function largestOfFour(arr) {
var largestNumberArray = [];
var highestNumber = 0;

for (var i = 0; i < arr.length; i++) {

largestNumberArray.push(highestNumber);

} 

return largestNumberArray;
}

OK. So I’ve written a really simple for loop up there, and most of us should be familiar with it by now. But what it’s set up to do is use i as a variable to iterate through the arr property. Arr being the four arrays present in largestOfFour. It iterates through all four because it detects how many arrays exist in arr using .length.

Inside of the for loop, I have my highestNumber variable being pushed into the empty largestNumberArray. Push() is one of those methods we haven’t talked about yet. So let’s deal with that now before we get into another method we haven’t yet seen.

The Push() Method

Push() is seen in a lot of programming languages and Javascript is one of them. Its function is usually the same across the board in that it’s used to add something to something else. Typically in Javascript, we use push() to add a value to the end of an array and returns its value.

So in this case, when we push the highestNumber onto largestNumberArray, we’re really adding whatever highestNumber happens to be into largestNumberArray. Ultimately what we’ll get from this is an array of the largest numbers in each of the arrays inside largestOfFour. Then we return the largestNumberArray after its had the largest numbers pushed to it.

Getting Back to the Loops

So, believe it or not, that was still the easy part. The next thing I have to do is evaluate all the numbers within each of those four arrays inside largestOfFour to determine which one is the largest. Now, I could write another–really messy–for loop, but thinking about it this whole time made me kind of sick. I did some research instead and got to a solution that seemed to be repeated over and over again: use reduce(). So here we go:

function largestOfFour(arr) {
var largestNumberArray = [];
var highestNumber = 0;

for (var i = 0; i < arr.length; i++) {

highestNumber = arr[i].reduce(function(a,b) {
if (a > b) {
return a;
} else {
return b;
}
});
largestNumberArray.push(highestNumber);

} 

return largestNumberArray;
}

Oh my gawd, what is going on up there? In this example, we use reduce() to evaluate the highest number using a function and if conditional that evaluates if value a (one number in the array) is greater than value b (another number in the array). Then, we’ll take the higher value from our conditional, send it through our reduce() method so we only end up with one value and slap it into highestNumber. From highestNumber, we’re going to make it throw its value into largestNumberArray so we can build a list of the highest numbers to validate this exercise.

Still confused about reduce()? Let’s find out what it is!

The Reduce() Method

I was going to link to the MDN documentation for this one too, but after actually reading it myself, the whole thing went backwards in my head. Truthfully, the documentation for any language isn’t always the most understandable thing out there–and it’s not just because it’s dry reading. Instead, I found this excellent, succinct explanation of reduce() that explains much better what it does and why we’re using it.

Essentially, we are reducing all the values within the array into one value that we can use. Any time you need to reduce a list of values to just one, reduce() might be just what you’re looking for.

The For Loop Solution Final

Here’s the final code.

function largestOfFour(arr) {
var largestNumberArray = [];
 var highestNumber = 0;
for (var i = 0; i < arr.length; i++) {
 highestNumber = arr[i].reduce(function(a, b) {
 if (a > b) {
 return a;
 } else {
 return b;
 }
 });
 largestNumberArray.push(highestNumber);
 }
 return largestNumberArray;
 }
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Run that and it’ll validate. Yippee! We did it!

Resources:

CPlusPlus on Ternaries
These magnificent people and C++ can explain so much of JS.

Reduce() on MDN
Kind of confusing explanation of reduce(), but perhaps it’s just me.

Gorka Hernandez, Find the Largest Number in an Array
Once again, Gorka has an excellent solution that I referenced, and it is using a nicer looking ternary operator instead of my if conditional.

StackOverflow, Finding Largest Number
StackOverflow discussion on finding the largest number in an array. The accepted answer is an interesting approach, a little heavy for me, but looks nice nonetheless.



Bonfire: Title Case a Sentence Solution

Today we’re going to capitalize the first letter in each word of a sentence. The Bonfire calls this one the Title Case a Sentence exercise. Like always, we’ll start this one off by visualizing it without code–basically writing pseudo code to lay out the steps for how we’re going to approach this problem.

Approaching the Problem

The Bonfire starts you off with this:

function titleCase(str) {
  return str;
}

titleCase("I'm a little tea pot");

It is all very familiar at this point. You’re looking to make each letter in the sentence that is at the start of the word an uppercase letter instead of its lowercase variant. Here’s how I imagine breaking this down:

  1. I want the first character of every word to be capitalized, but I can’t modify the string. So one of the first things I want to do is split the sentence into an array of words. The array can tell when to make a new array item based on the spaces between each word in the sentence. I can probably use split() for this.
  2. Next thing I want to do is check each of the items in my array and detect the first character of every item. That character will then be set to uppercase. I can use .toUpperCase() for this.
  3. And since I can’t return an array that will validate because the Bonfire expects a string, I’ll have to join all the items in the array back into a string. I’ll use join() for this.
  4. Now, I know Bonfire is going to doublecheck my answers not just on the string it gives me in the provided code, but I’ll probably have to worry about what happens when all the characters in the string are uppercase or there’s alternate case situations too. I might have to figure out a way to target all the characters after the first one and force all those to be lower case using toLowerCase().

I know some of the above methods because we’ve used most of them before. We’ve used split() and join() together to deal with strings and manipulating them. And we’ve used toLowerCase() as well. The only one in the above process that’s new is toUpperCase(). And if you already know a method called toLowerCase() exists, you can be pretty sure that its opposite also exists for use. Let’s go ahead and start writing this out.

The For Loop Solution

The for loop solution is probably the one that requires the least amount of code that I could come up with. I’m going to combine two methods in my initial approach to save on some space and the two methods I’m combining are split() and toLowerCase(). Anytime I can kill two birds with one stone when it comes to typing code, I take it. The less code there is, the less chances I have of screwing something up. Here’s what I got:

function titleCase(str) {
  var titleStr = str.split(' ');
  
  return titleStr;
}

titleCase("I'm a little tea pot");

I created a local variable called titleStr to work with inside of the titleCase() function. titleStr becomes str while it is being worked on inside the function. Then I split the string into arrays and load the array up by the word using the space between each word as a marker to split each array item. So, the array I end up with looks like this:

(I’m, a, little, tea, pot)

Now we’re going to write our for loop to locate the first character of each array item and replace it with an uppercase character using toUpperCase(). Here’s what I got:

function titleCase(str) {
    var titleStr = str.split(' ');
    for (var i = 0; i < titleStr.length; i++) {
        titleStr[i] = titleStr[i].charAt(0).toUpperCase();
    }
    return titleStr.join(' ');
}
titleCase("I'm a little tea pot");

We’re starting off with a for loop that iterates through the titleStr array that contains all the words of our original string. As we loop through the array, we’re checking for the first character of each word. In the for loop, each word is represented with titleStr[i] and charAt(0) locates the first position of each of those words. Once it locates the first character in a word within the array, it changes the character to uppercase using toUpperCase(). Then we return titleStr as a string by using join() to put the array of words back into a normal string.

So this is a good start, but we’re not done yet. Not content with keeping this simple, the Bonfire will check us against strings such as hONEY, i’M hOME or WELCOME TO DISNEYLAND. They’re doing this so we don’t just call toUpperCase() on the string and call it a day. So, we really do need to address not only the first character in each word, but the rest of the word as well. To do this, I’m going to introduce a new method we haven’t worked with before called slice().

A Bit About Slice()

Slice is a method used on arrays to return a portion of a sequence, within slice we can specify a value that is a negative or positive integer. If no value is specified, it will assume 0 by default.

Slice also takes in more than one integer and can be used to specify a range. So if you wanted to, let’s say select the second to sixth within a sequence, you would specify something like this: .slice(1,5). Where one is the second item in the array, and five is the sixth. This will make slice select all within that range up to the fifth element (2, 3, 4, 5).

Slice() also takes negative values which will typically begin at the end of an sequence. So declaring .slice(3, -1) means it will select the fourth item to the second last item within the sequence.

Finally, if you don’t specify a second value, slice() will start selecting where you specified the first value and continue selecting until it hits the end of the sequence. In this Bonfire, we’re going to use slice() to select starting at the second character in our words and continue through the end of each word. So for example, in the word “bird”, we would be declaring, .slice(1) which would select the bold portions of the word: bird.

Finishing the For Loop Solution

Here’s the code with slice in place. Notice that we’re adding another pass to our code that addresses the rest of the word. Slice() starts looking at the word at position 1 (or the second character) and proceeds to set all subsequent characters to lower case using toLowerCase(). All this is still being done in the same basic for loop we started before. Here’s the final code:

function titleCase(str) {
    var titleStr = str.split(' ');

    for (var i = 0; i < titleStr.length; i++) {

        titleStr[i] = titleStr[i].charAt(0).toUpperCase() + titleStr[i].slice(1).toLowerCase();

    }

    return titleStr.join(' ');
}

titleCase("I'm a little tea pot");

Run that through and it’ll validate.

Resources

MDN Array.prototype.slice()
Goes over Slice() and how it works, plus includes handy examples.



Bonfire: Find the Longest Word Solution

We’re looking for the longest word in a string today and slowly getting more familiar with how to approach algorithms by breaking down problems in a human readable fashion. Remember in math tests when you would have to come up with equation to solve a word problem? Those typically went something like: “Jack has two apples and decides to split them to share with his friends Alissa and George. If George gets 3/4 of an apple and Alissa gets 2/3 of an apple, how much apple does Jack have left?”

Not the greatest word problem up there, but hopefully you get the gist. Writing algorithms for programs isn’t too much different than interpreting and coming up with solutions for math word problems. You essentially have to break things down into logical steps and approach the problems one step at a time. Finding the longest word in a string is a good exercise to really break down this thought process.

Approaching the Problem

Free Code Camp’s Bonfire starts you off with this:

function findLongestWord(str) {

    return str.length;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

You have a function, you have a string fed into that function and the task is to locate the longest word within that string and return how many characters are in it. If you’re proficient with English, you already know the answer to this without having to write a program to solve it, the longest word is ‘jumped’ and it has 6 characters. But how do we approach this answer programmatically?

Let’s think about what we’re tasked to do here. We have to find the longest word in a sentence. If you were asked to do that normally, this is what you would probably do to come to the conclusion–without using an programming, just basic problem solving skills:

  1. You would look at the sentence.
  2. You would look at each individual word and count how many letters are in each.
  3. You would compare your letter counts for each word and determine which word has the most characters.
  4. You would name which word you discovered to have the most letters–and therefore, is the longest word, and declare how many letters it has.

Already, we’ve laid out a game plan to write our algorithm to solve this problem in four steps. If we took our problem solving solution above and translated it to JS pseudocode, we might have an approach that looks like this.

  1. Take in the string via the function. Split the string into an array at each space. This will allow for counting and comparison because strings are immutable and arrays can be manipulated.
  2. Set a longestWord variable that is empty to use as a comparison variable when we compare each of the words. Eventually load this variable with the longest word discovered in the string.
  3. Loop through the words contained within the split up array and compare each word to determine which one has the most characters.
  4. Set the longest word into the longestWord array and return the character count value of the longest word discovered while looping.

Finding the Longest Word With a Loop & Conditional

So we have a logical approach and a bunch of pseudo code. Let’s head into the actual code now and approach this one step at a time. I’ve double checked this approach because I wasn’t too sure about it and I was pretty much on the right track. I refined what I had my notes to more closely match these two solutions: Gorka Hernandez’ Solution and Alexandrebvd’s Solution

First thing’s first, we know we have to split up our string into manageable chunks. Specifically, we need an array that holds each word within our sentence. Therefore, we need a way for the array to use split(), and split() should know to create a new array at each space it encounters in the string.

A Quick Note About Substrings

Within the split() method, we can specify that the string be split at each space by dividing it up into substrings. In very simple terms, a substring is a portion or part of a string. So if you had a string that was, “Andy likes apples”, then some examples of substrings for that string would be “Andy” “likes” “apples” or “And” “yli” kes” “app” “les” and so on. Substrings are useful because you split strings up in various ways to manipulate them, check them, and more.

For this particular exercise, we actually do need to split our string up into substrings, and using the split() method we can specify that it substrings our string based upon spaces. That is to say, every time split() encounters a space, it will create a new substring.

So our string: “The quick brown fox jumped over the lazy dog”

Will be substringed using split() into: “The” “quick” “brown” “fox” “jumped” “over” “the” “lazy” “dog”

Notice above that we’ve split the sentence into individual words. That’s exactly what we want in order to count each of those words. So let’s dive back into the code and split our string up:

function findLongestWord(str) {

var splitStrArray = str.split(' ');

return str.length;
 }
findLongestWord('The quick brown fox jumped over the lazy dog');

In the code above, I’ve created an array called splitStrArray. That array is going to be populated with substrings that are a result of whatever str is when each of its components has been split every time the split() method encounters a space in str. Please note the space between the two quotes. This space is very important because it tells split() where we want it to split our string up.

Next thing I’m going to do is create an empty string variable that will hold whatever the longest word will be. This will also be the variable that we perform checks on using our loop and the variable we’re going to use to return the character count to validate the exercise:

function findLongestWord(str) {

var splitStrArray = str.split(' ');
var longestWord = '';

return str.length;
 }
findLongestWord('The quick brown fox jumped over the lazy dog');

longestWord is set to nothing right now, because it will be filled with whatever our loop discovers to be the longest word in the string. Now that we have the set up out of the way, we’ve satisfied the first two steps in our pseudocode/problem solving steps. Our next step is to write out our loop:

function findLongestWord(str) {
  
  var splitStrArray = str.split(' ');
  var longestWord = '';
  
  for (var i = 0; i < splitStrArray.length; i++) {
    
  }
  
  return longestWord.length;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

This for loop is pretty standard right now, and in the old track on Free Code Camp, when we were still going through Code Academy’s JS course, they’ve had us loop through an array a few times. A few of those times to check the length, or to iterate through the array looking for a specific character or word. We’re doing a similar thing above in that we’re looping through the splitStrArray’s substrings based on the length of each substring or word that was pulled from str.

Right now all we’re doing is looping through each substring. We’ve validated a part of step 3, so we need to finish it off by counting each of the substrings we’re looping through, loading the words it finds into longestWord, and then checking each longestWord against each substring to find the longest word or substring. We can accomplish this using a simple if conditional nested inside of our for loop. Incidentally, this is also our finalized code:

function findLongestWord(str) {

    var splitStrArray = str.split(' ');
    var longestWord = '';

    for (var i = 0; i < splitStrArray.length; i++) {

        if (splitStrArray[i].length > longestWord.length) {
            longestWord = splitStrArray[i];
        }

    }

    return longestWord.length;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

Up there, we’ve got a if statement that checks the total length of each substring in the splitStrArray array against the longestWord string’s length. If if finds a word within splitStrArray that is longer than whatever longestWord’s length is, then it changes longestWord to that word. It continues to do this and perform the check until it loops through all of the substrings within splitStrArray. At which point, it should have the longest word while at the same time, have checked through the entire array.

The Step Through

Here’s the step through for a better visual of what’s happening:

Pass 1:
splitStrArray[0] = “The”
longestWord = “”
splitStrArray[0] > longestWord = true
set longestWord = splitStrArray[0]
longestWord = “The”

Pass 2:
splitStrArray[1] = “quick”
longestWord = “The”
splitStrArray[1] > longestWord = true
set longestWord = splitStrArray[1]
longestWord = “quick”

Pass 3:
splitStrArray[2] = “brown”
longestWord = “quick”
splitStrArray[2] > longestWord = false
longestWord = “quick”

Pass 4:
splitStrArray[3] = “fox”
longestWord = “quick”
splitStrArray[3] > longestWord = false
longestWord = “quick”

Pass 5:
splitStrArray[4] = “jumped”
longestWord = “quick”
splitStrArray[4] > longestWord = true
set longestWord = splitStrArray[4]

longestWord = “jumped”

Pass 5:
splitStrArray[5] = “over”
longestWord = “jumped”
splitStrArray[5] > longestWord = false
longestWord = “jumped”

Finally at the end of splitStrArray, it should evaluate the last substring in the array which would be “dog”, the if statement will evaluate to false because the length of “dog” is shorter than the length of “jumped”. The loop exits because there are no more substrings to evaluate or iterate through and the function will return the length of the longestWord string variable, which in this case should be “jumped”. Jumped has six characters, so its length should return as “6”. The Bonfire will validate and pass.

Resources

Gorka Hernandez Blog, Finding the Longest Word
Gorka also explores this Bonfire solution using functional programming in addition to the loop solution. The alternative solution involves the use of reduce. Good for a bit of tinkering if you’re interested in jumping ahead or getting into the functional programming concept.



Bonfire: Check for Palindromes Solution

We’re going to check for palindromes today for one of our Bonfire challenges. This is something I haven’t done yet. I have two solutions this time. The first relies on pre-existing methods. The second is a for loop.

Approaching the Problem

Let’s first take a look at what we’re given.

function palindrome(str) {
  // Good luck!
  return true;
}

palindrome("eye");

Simple and familiar set up by now. A basic function with a function call. I’m a particular fan of the somewhat cheeky, “Good luck!” in there. All right, first of all, a palindrome is a word or phrase that when reversed is the same as it was prior to reversal if you ignore spacing, capitalization and punctuation. For instance:

racecar = racecar
eye = eye
tacocat = tacocat

And my personal favorite because I am apparently still a thirteen year old:

abutttuba = abutttuba

On the flipside, the following words and phrases are not palindromes:

deerrun = nurreed
hockey = yekcoh

We already know that we have to evaluate whether a string is a palindrome or not, and the Bonfire gives us a clue right off the bat in the challenge description: ignoring spacing, capitalization and punctuation. Now we know that even though the function call only references the palindrome “eye”, the Bonfire is serious about us doing this right so we’re likely to be tested against palindromes with things like spaces, capitals and punctuation too. Something like this:

Degas, are we not drawn onward, no? In union, drawn onward to new eras aged?

This means we’re probably going to have to strip capitalization, punctuation and spacing from whatever the Bonfire throws at us.

Next thing we have to consider is that we need to be able to check the reversed string to its unreversed state. Believe it or not, we did something similar to this for the the Reverse a String Solution where we converted the string into an array, reversed the array, then turned it back into a string. We can do the same thing to help us check for palindromes in this scenario.

Finally, we need to return a true or false value depending on whether the string evaluates a palindrome or not. Let’s get started on the pre-existing methods solution:

Checking for Palindromes Using Existing Methods

The first thing I’m going to address is the stripping of punctuation, capitalization and spaces from the string. I’m going to do that using a couple of pre-existing methods. The first is toLowerCase() which removes capitalization by forcing all characters to be lowercase. The second is a replace() function that will remove spaces and punctuation.

toLowerCase() is pretty self explanatory, but I think I need to take a moment to comment on how we’re going to use replace(). Here’s what I’ve got at this stage:

function palindrome(str) {
  var stripStr = str.toLowerCase().replace(/\W|\s/g,'');
}

palindrome(“Degas, are we not drawn onward, no? In union, drawn onward to new eras aged?”);

With replace(), we’re going to come back to something you should have been introduced to shortly before the Bonfires; Regular Expressions. Before we get to that though, let me explain my approach. The first thing I did with this is create a local variable within the function that is meant to strip the string of capitals, spaces and punctuation to make finding the palindromes easier.

With toLowerCase() I’m achieving that by using a pre-existing method to force all capitals in whatever string I feed palindrome() to become lowercase. Then I use replace() coupled with regex to filter out spaces and special characters. Within Regex, //g is used to represent a global search. What I’m doing is executing a search for all non-word characters with \W, and searching for spaces with \s.

After that, the comma and ” is meant to replace whatever is found for special characters and spaces with–basically nothing. Not even a space. This effectively cleans up whatever string we’re going to feed palindrome() and I chose the particularly meaty one we met earlier because it has all the components the Bonfire is probably going to look for when it attempts to validate our solution. At this point in time, our string that was originally: Degas, are we not drawn onward, no? In union, drawn onward to new eras aged?

Now probably looks more like: degasarewenotdrawnonwardnoinuniondrawnonwardtonewerasaged

Next step is to actually check for the palindrome itself. There’s actually two approaches to this, the first is a fully automated one using all pre-existing methods (particularly our friends, split(), reverse() and join()), which I was going to cover, but Wulkan from wulkan.me has already done a pretty good job of that. Mine only differs slightly, but here it is:

function palindrome(str) {
  
  var stripStr = str.toLowerCase().replace(/\W|\s/g,'');
  var checkStr = stripStr.split('').reverse().join('');
  
  if (stripStr === checkStr) {
    console.log("the string is a palindrome.");
    return true;
  } else {
    console.log("the string is not a palindrome.");
    return false;
  }
}
  
palindrome("Degas, are we not drawn onward, no? In union, drawn onward to new eras aged?");

What we’re doing is first stripping the string of capitals, spaces and punctuation. Then since we now have:

degasarewenotdrawnonwardnoinuniondrawnonwardtonewerasaged

Which is still a string–and therefore, immutable, we need to reverse it to check for palindromes. Otherwise, you’re just checking the existing string against itself. So we use our good friends, split(), reverse() and join() to flip the string around. Finally, we use a simple if statement to check if stripStr and checkStr are deeply equivalent to each other. If they are, we return true. If they aren’t, we return false. You can replace the palindrome() parameter above with eye prior to validating if you wish, but the Bonfire should check the solution and issue you a pass whether you check for eye or check the above palindrome.

Checking for Palindromes With a For Loop

Let’s say you’re not really sure what those existing methods are doing and would rather step through this in a more “show your work” type of way. I’ve done a for loop solution for this, again, not sure if it’s really great, but it validated and seems to handle the Bonfire requests pretty well.

Here’s the problem I faced as I was thinking through this one myself. Despite my lofty goal of using no build-in methods, I still have no clue as to how to strip capitals, spaces and punctuation from a string without using the existing toLowerCase() and replace() methods. There are also a lot of solutions to the popular “check for palindromes” interview question online without relying on built-in methods. However, many of the solutions offered only check whole words for palindromes, not necessarily phrases. So in terms of prepping the string for a palindrome check, I started out the same:

function palindrome(str) {
var stripStr = str.toLowerCase().replace(/\W|\s/g,'');
}
palindrome("Degas, are we not drawn onward, no? In union, drawn onward to new eras aged?");

I’m still creating a stripped down string using toLowerCase() and replace() with regex, and the Bonfire specifically alludes to these two methods so for this particular approach, I assume that those two methods are OK to use in this case. From here, we can get to a palindrome check using a for loop.

function palindrome(str) {
    var stripStr = str.toLowerCase().replace(/\W|\s/g, '');
    for (i = 0; i < stripStr.length; i++) {
        if (stripStr.charAt(i) != stripStr.charAt(stripStr.length - 1 - i)) {
            console.log("the string is not a palindrome.");
            return false;
        }
    }
    console.log("the string is a palindrome.");
    return true;
}
palindrome("Degas, are we not drawn onward, no? In union, drawn onward to new eras aged?");

All right, let’s step through this one slowly. We already know stripStr is removing the special characters, spacing and capitals from the string we’re checking. Once we have that, we head into a for loop.

The for loop iterates through i which is set to continue looping until i is greater than the length of stripStr. This ensures that we check all characters within the string and iterate through each as well. Inside of the for loop, we have an if conditional that checks both ends of our string. stripStr.charAt(i) begins at the start of the string, and stripStr.charAt(stripStr.length – 1 – i begins at the end of the string. charAt() is a method that checks the character at the specified parameter. Technically, you might refer to these as pointers on either end of the string, but I’m not confident if that’s really the terminology we want to use.

Regardless, the subtraction portion at the end ensures that we move through backwards iteration as we subtract 1 each time we loop through. In other words, each iteration moves one further into the string, either right or left, as the loop iterates through stripStr’s length. As the loop moves through, we check each character to its equivalent partner on the other end.

Here is a partial step through as I understand it:

Pass 1:
i = 0
Add 1 to stripStr.charAt(beginning)
degasarewenotdrawnonwardnoinuniondrawnonwardtonewerasaged
Subtract 1 from stripStr.charAt(end)

Pass 2:
Add 1 to stripStr.charAt(beginning)
degasarewenotdrawnonwardnoinuniondrawnonwardtonewerasaged
Subtract 1 from stripStr.charAt(end)

Pass 3:
degasarewenotdrawnonwardnoinuniondrawnonwardtonewerasaged
Add 1 to stripStr.charAt(beginning)

Subtract 1 from stripStr.charAt(end)

And on and on it goes until the two pointers reach the other end and have evaluated the entire string against each other. If the entire string matches on either end all the way through, our function returns true. If, at any point, there is a discrepancy and one of the characters doesn’t match the other character on the other end, our function returns false. Plug it into the Bonfire and it will evaluate appropriately.

A Faulty Sidetrack

What I attempted prior to checking for false was checking for true where:

if (stripStr.charAt(i) === stripStr.charAt(stripStr.length - 1 - i))

This evaluates perfectly for nearly everything except for a two-middle character non-palindrome such as almostomla, where it inaccurately evaluated the s and t and returned true for palindrome. Changing the deeply equivalent to deeply false resolved this issue and I’m frankly still trying to figure out why. If you have an explanation, let me know!

Bonfire’s Added Underscore (Update: 04/24/2017)

It would appear that I had a situation with my solution where the underscores the Bonfire threw at it would cause the code not to validate. The regex wasn’t written to recognize underscores, even though \W takes care of dashes. So, a quick fix for this would be to add an underscore selection to our regex. This isn’t the prettiest thing I’ve seen, but it’ll do: /\W|\_|\s/g

That means our updated solution would look like this:

function palindrome(str) {
  
  var stripStr = str.toLowerCase().replace(/\W|\_|\s/g,'');
  var checkStr = stripStr.split('').reverse().join('');
  
  if (stripStr === checkStr) {
    console.log("the string is a palindrome.");
    return true;
  } else {
    console.log("the string is not a palindrome.");
    return false;
  }
}
  
palindrome("Degas, are we not drawn onward, no? In union, drawn onward to new eras aged?");

Shout outs to Paul and Mike in the comments for pointing this out! And a sincere apology to Paul for getting to this so, so, so much later than I really meant to.

Resources

JSPerf, Is Palindrome?
Benchmarking solutions to check for palindromes. These show you efficiency specifically related to Palindrome checking. Great if you want to browse.

JSBeautifier
I’m always annoyed every time I copy and paste my code from Bonfire or my text editor into WordPress that it inexplicably loses all its formatting. So JSBeautifier really deserves a shout out.

StackOverflow, Check in JS for Palindromes
Great resource with tons of different solutions.

Regex Tester
If you ever thought to yourself, “Gee, I get way too much sleep at night and don’t have enough stress in my life”, get into Regex. It’s all around us! Regex101 is a good tool to use to test out the regex you write to see what it will and will not select.



Bonfire: Reverse a String Solution

It seems my previous Bonfire post has been fairly popular, so I figured I might as well share some of my other solutions in case someone might find it useful. This time, I’m tackling the Bonfire prior to the Factorializing one.

These solutions aren’t necessarily the best, most efficient way of solving the Bonfires. They’re just my approach to the problem. Within programming, coding and development, there’s usually multiple ways to solve the same problem. And depending on the philosophy of the coder, they might view certain approaches as more ideal than others. I’m just presenting what I have in case it helps someone.

Approaching the Problem

So the Free Code Camp Bonfire starts us off with the following code:

function reverseString(str) {
  return str;
}

reverseString('hello');

Already we see that we need to use a function that takes a parameter of str. Str in the function call has a value of “hello”. So, we are going to have to figure out how to reverse the string, “hello”. Having gone through the old Free Code Camp (they updated their lessons sometime in late-August) track that involved moving through Codeacademy’s JS course, we’ve encountered this problem before.

What I did for that solution was I separated the string by the letter and loaded them into an array. From that array, we can rebuild the string but backwards this time using a for loop. While this works, it’s hardly efficient and has us writing a ton of convoluted code to do something relatively simple.

Here’s what exists within JS to allow us to do this more efficiently. There are three pre-made functions within JS: split(), reverse() and join(). We can combine all three of these to quickly split up the string into an array that will resemble: [h, e, l, l, o], reverse it and turn it into [o, l, l, e, h], then join it back into a string: “olleh”.

The Immutable String Issue

Why do we need to turn the string into an array? Strings in JS are immutable. Immutable elements cannot be modified after they have been created.

So in the above code, str is set to a string that says “hello”. We cannot actually modify hello because it is immutable. That means, we can’t even do something as simple as reverse the string. To get around this, you have to turn the string into an array, reverse the array, then join the array back into a string. Because you join the array back into a string that will then say “olleh”.

Reversing the String & Returning It

Now we need to do all this in one step and on the str parameter. To combine functions you use the . (dot) operator. So it should look like this:

return str.split('').reverse().join('');

The above code is doing exactly what I said in the previous section. It is taking whatever str is, splitting it into an array. Then it reverses the array, then joins the array back into a string. Using a pre-built function allows us to sidestep the messy exercise of writing a loop.

So overall, this is what the final code looks like:

function reverseString(str) {
  return str.split('').reverse().join('');
}

reverseString('hello');

All this gets returned outside the function and the console in the Bonfire should return “olleh” and validate all the conditions.

Resources

Ten Ways to Reverse a String in JS, Edd Man
Really good resource for exactly what we’re facing in this Bonfire. It also includes the above solution using pre-built functions as well as a few other approaches using various loops. And one example using recursion if you really felt like it.

How Do You Reverse a String in Place in Javascript, StackOverflow
Excellent resource and discussion on how to reverse a string.



Bonfire: Factorialize a Number Solution

I’m going through FreeCodeCamp’s coding track as a way to brush up on Javascript, and re-familiarize myself with its more programming-centered features. I have been using Javascript primarily with websites. Most of the time, I’m not dealing with anything beyond timing, detecting user actions and maybe a little bit of animation. So and wanted to branch into more web application development. It’s also a good excuse to remind myself of programming practices without relying 100% on Swift–a language I’m still learning and is a few degrees more complex, versus doing it with Javascript–a language I’m more comfortable with.

I was cruising along fine with my skills map. A large proportion of the first few lessons centers around Codecademy’s online Javascript track. When I finished it up, FreeCodeCamp introduces the concept of Paired Programming and Bonfires. I decided to look into a couple of the the Bonfires on my own. The first three were pretty standard challenges. In fact, #1 and #2 weren’t actual challenges. #3 took a tiny bit of research and I had encountered it before while learning C++. Then I hit the fourth, where it tells you to Factorialize a Number. It was a great exercise that made me think outside of my comfort zone. After trying some really sloppy loops, I ended up with a recursive function.

I’m going to show both of my approaches to this one, first with the recursive function and second using a for loop. I’ve seen both approaches, and I’m by no means an expert at this. I just want to store my attempts at these challenges and walk through them to gain a better understanding. And if it helps someone else understand it too, then great!

Let’s Factorialize a Number

The first thing I had to establish was what factorializing a number is actually about. The explanation was clear cut enough, but being a math dummy, I had to question myself every time I looked at it. And it was as simple as it seems. In laymans terms, when you factorialize a number, you are multiplying that number by each consecutive number minus one. So for example, if your number was 3. You would have something like this:

3! = 3 * 2 * 1

There’s a pretty easy pattern for this:

0! = 1
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1

And on and on, so by the time you reach, let’s say, 9 for example, you might have this:

9! = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

Factorials are expressed in shorthand as x!, so when you see a number or value with an exclamation mark, you should know that we’re looking at factorials. Now that we kind of understand how that works, we can try to express that in code.

Breaking It Down With a Math Dummy

I said it before, and it needs to be said again. I am bad at math. Terrible at it. I don’t know if it’s because of the way math was taught to me, or what. But me and math don’t go well together. However, even if you are as terrible at math as I am, this one is solvable! So here’s how I broke it down. The Bonfire on FreeCodeCamp starts you off with this:

function factorialize(num) {
  return num;
}

factorialize(5);

Right off the bat, you know they want you to factorialize 5. They also want this written inside of a function called “factorialize”. That’s stuff we already know. So here’s what I was thinking…

1. Since we are essentially looking at determining what num is and then multiplying it by each consecutive number minus one, that can expressed like this num(-1). We need to stop it when num is equal to 1 because going further means hitting 0.

2. In factorials, 0! is always 1. Because multiplying by 0 will frequently return 0, we need to have an exception to prevent that from occurring when the function runs. So we probably need an if conditional statement that checks for 0 and returns 1. Since the conditional will check for and weed out 0, anyway, it might prevent num(-1) from ever getting there.

3. I’ll weed out 0 with the if conditional first. Then deal with num(-1) in a recursive function–which is kind of a hairy exercise for people might be completely new to coding.

Writing Out the Code

Let’s start by doing Step 1 under the break down above. I’m going to weed out the incidence of hitting 0 using an if conditional.

function factorialize(num) {
  if (num === 0) {
         return 1;
      }
}

That was the easy part. What this does is evaluate num. If it detects num is equal to 0 at any point, it will run the statement inside of the if conditional and return 1. Dealing with the recursive function next is where it gets tricky. Though the code is minimal, sometimes the most minimalist of things are the most complicated.

function factorialize(num) {
  if (num === 0) {
         return 1;
      }
   return num * factorailize(num-1);
}

Oh boy, recursive functions. This is something I see in Swift and it always makes me go cross-eyed. Recursive functions run inside of themselves. So you might run a non-recursive function and it spits out a return value and you move on with your life. If you run a recursive function, it spits out a value that gets run again within the function, spits out another value which then gets run again in the function, spits out another and gets run again…on and on until it exits the recursion.

It’s hard to visualize this for me, but the best way is to remember sixth grade math and the order of operations (which, funny enough, is a core component of programming). Within the hallowed rule book of order of operations, you would perform the calculations inside of the parenthesis first. So if you had a formula like this:

(5 * 6) + 9 = n

You would do 5 * 6 first, then take the value you got from that and add 9 to get n. A similar thing is happening with our code. We are first taking num, subtracting 1, then using that value to multiply by num.

So if you had num set to 5, we would be returning this on factorialize()’s first pass:

5 * (5-1)

Second pass:

5 * (4-1)

Third pass:

5 * (3-1)

Fourth pass:

5 * (2 -1)

Fifth pass:

5 * (1-1)
return 1
5 * 1

During the fifth and final pass, our function falls into the if conditional. It returns 1 which num will multiply itself with and the function will exit with a total value.

In the case of factorialize(5). You should get 120. So, the final code all written out:

function factorialize(num) {
  if (num === 0) {
  return 1;
}
     return num * factorialize(num-1);
}

factorialize(5);

We pass a parameter of 5 to factorialize(). It takes it into the function as num and checks if num is equal to 0. If num is equal to 0 it returns 1 and factorializes it as 5(1), where it will stop the recursion. If it’s not 0, it takes num and multiplies it by whatever num-1 is and continues to perform this action until num is equal to 0. The final return is the factorialization of the number 5 that we passed into factorialize(). That number should be 120.

The For Loop Alternative

A for loop will also work as a solution to this Bonfire. There might be other solutions too, because a lot of problems in code can be solved multiple ways depending on style, approach and preferences. I just don’t know of any others. I had actually written a for loop that validates on Free Code Camp and technically does the same thing. I’ve seen others use this approach as well. Though it’s quite a bit more legwork. Here it is:

function factorialize(num) {
  
  for (var i = num - 1; i >= 1; i--)
    num *= i;
  if (num === 0) {
    return 1;
  } else {
    return num;
    }
}

factorialize(5);

Above, we have a for loop within factorialize() that will continue to run so long as i remains greater than or equal to 1. In the above for loop, we make i equal to num -1. Then check if i is still greater than or equal to 1. If it is, then subtract 1 from i, and run the block of code. Within the block, we take num and multiply it by whatever i is. Then we return the result, which in this case should be 120.

More recently (or I could have just overlooked it), FreeCodeCamp added a check for 0 (thus foiling my plans) so I added an if conditional to check for 0 and return 1 if num === 0 ever evaluates to true. Thanks go out to Lena for bringing this to my attention in the comments.

I have a feeling there’s a more elegant way to express this in the For Loop so if you have alternatives or suggestions let me know!

Resources

Bonfire: Factorialize a Number – luishendrix92
One of the more amusing explanations of what a recursive function is. This approach is pretty close to what I got, but it features a check for 1 as well as 0. I’m not sure if you really need that check for 1 and if I’m missing out on anything by not checking for 1 in my own solution. Or it could be another case of different approaches, different styles.