Category: Javascript Joy



Javascript Problem Solving: Fibonacci Sequence

It should come as no surprise that a Fibonacci Sequence is a common test deployed on candidates during interviews for software or development related jobs. As a front-end developer, I hardly encountered these types of tests as the usual interview question often involved building out UI/UX components or working through a design problem. But it’s all in the interest of learning Javascript on a deeper level.

Typically in a whiteboard scenario, problems like this one are handed to the candidate and they’re asked to show their thought process while solving it. Fibonacci is a common computer science problem, typically introduced to students in the first semester. Since many programmers nowadays are self-taught, a lot of us tend to be blindsided by whiteboard tests. That is not to mention the vast majority of people blank on problems during an interview when they are asked to solve a programming problem while there are a bunch of other people watching.

So, while we’re here and not being faced with a panel of interviewers, let’s talk about Fibonacci and how to go about solving the problem.

What is Fibonacci, Anyway?

Fibonacci is often referring to a number sequence that starts with usually 0 or 1 and each subsequent or following number is the sum you would get from the previous two. So, here’s a Fibonacci Sequence written out:

0
0+1 = 1
1+1 = 2
1+2 = 3
2+3 = 5
3+5 = 8
5+8 = 13
8+13 = 21

And onward. Usually you would be asked to output the sequence up to a certain number. Or to write a function that spits out the sequence when a number is thrown out. So let’s think this one through.

Thinking It Out

  1. Since we know that this is a sequence and if we’re expected to spit out a sequence up to a certain number, we already know we need to use a loop to accomplish that. This loop will test to make sure we’re below or at the specified number and then stop once it reaches that point.
  2. It would be a good idea to utilize arrays in order to hold our initial number sequences and the output of the number sequences.
  3. Finally, it seems deceptively simple that we would have to add the first sequence number to the second sequence number. But if we’re working within arrays and loops, we might have to do some fancy footwork to get the proper array numbers to perform math operations on them.

Writing Our Array and Our Variable

Like with most other problems, I like starting with the easiest thing first and worrying about the rest afterward. The easiest thing for this would be writing the array. So let’s get that out of the way. I’m also going to assume that we don’t need any kind of user input and that we’ll just feed the console the sequence number we want, so we’ll need a variable that will feed how many numbers we wish to have. This trims out some peripheral stuff. Let’s get the array and variable in there, shall we?

var number = 10;

var fibArray = [0, 1];

Super easy. I created a variable called number. Number can be populated with any value. I picked 10, but we can change that to whatever we’d like depending on how long we want our Fibonnaci sequence to be. Next I created an array called fibArray which currently holds our two starting values: 0 and 1.

Writing the Loop

We know that for whatever number’s value is up there, that we need to loop through that many times. So, easy thing out of the way first:

var number = 10;

var fibArray = [0, 1];

for (var i = 2; i <= number; i++) {

}

You probably noticed that I initialized i with a value of 2 instead of the usual 0 or 1. This is because I want it start beyond 0 and 1 when it begins calculating our sequence seeing as 0 and 1 are already taken care of in the fibArray. Now we’re at the technical part. I need to create a math operation that will work to calculate our sequence. Fibonacci numbers are calculated by the first sequence number to the second sequence number.

If we look at what we’ve got so far, I declared fibArray with preloaded 0 and 1. Our loop is going to have to perform a math operation to get the next number in the sequence. It’s going to pull the numbers from the initial values we provided in fibArray. So, I’m going to have to tell fibArray to pull its value in the 0 and 1 position (which, incidentally, are 0 and 1).

My math operation is going to look something like this:

fibArray[i - 2] + fibArray[i -1]

What’s happening up there is we’re going into fibArray and referencing i. What we want is to increment the two numbers for the sequence differently which is where -2 and -1 come in. fibArray[i – 2] is actually referencing the number in the 0 position. And fibArray[i – 1] is referencing the number in the 1 position. This way, as our loop runs through, it increments i to the next value in the array, but will slowly loop forward in the array each time, and each time i will go back two spaces and one space, add them together and return the next number in the sequence. Here’s the code as it stands right now, with the above math operation in place. I’ve added a variable to hold the value from the operation:

var number = 10;

var fibArray = [0, 1];

for (var i = 2; i <= number; i++) {

var addFib = fibArray[i-2] + fibArray[i-1];

}

The Solution

Finally, let’s add this sequence number from our above math operation to our fibArray array. This is done so our loop has the next number for it to work through:

var number = 10;

var fibArray = [0, 1];

for (var i = 2; i <= number; i++) {

var addFib = fibArray[i-2] + fibArray[i-1];
 fibArray.push(addFib);

}

console.log(fibArray);

I added a push method up there to push the resulting number for addFib into the fibArray. Finally, I log fibArray to the console so we can actually see the sequence we get from it and we’re done!



Problem Solving With JS: The FizzBuzz Test

An interesting article I came across recently talked about the use of FizzBuzz, a programming test question often employed in interviews. The essential question is something to the tune of:

Write a loop that runs from 1 to 100. For every number that is divisible by 3, log Fizz to the console. For every number that is divisible by 5, log Buzz to the console. For every number that is both divisible by 3 and 5, log FizzBuzz to the console.

There was also an interesting conversation about programmers in interviews being unable to solve the FizzBuzz test on a super interesting place most people have probably heard of: Coding Horror (if you haven’t, I definitely recommend checking it out if you’re into code). So I wanted to take a step through the approach to lay out how I solve the test and why.

I’ll be writing it up in Javascript, but the same approach can be applied to most programming languages. I also want to disclose that this is not the most elegant solution. It’s just my approach to it.

Approaching the Problem

  • We already know that the test is asking us to write a loop that counts from 1 to 100, so that part of it should be simple. A  for loop is what I’m going to go with.
  • There are three things we need to test for here. If something is divisible by 3, if something is divisible by 5 and if something is divisible by both 3 and 5. An if statement that checks for the remainders should do the trick here.
  • Finally, we just need to console.log a number, Fizz, Buzz or FizzBuzz depending upon the results.

Writing the For Loop

If you’ve been familiar with some concepts of programming, you should already know about For Loops and have a basic understanding of what it’s for and how it’s supposed to look. For Loops exist in most programming languages in a very common manifestation. They essentially state that a variable that starts with 0, it should loop for as long as its value is less than a certain number, as it loops it should increment or (decrement, etc. in some cases) every time it loops.

Here’s the for loop I would set up for FizzBuzz:

for (var i = 0; i <=100; i++) {

console.log(i);

}

So, we’ve set up a for loop that says that for each loop through i, check to see if it’s less than or equal to 100. If it is, then add 1 to i’s value and log out the value of i using console.log(). This gets us through the first part of the FizzBuzz test. Let’s head into the next step, which is to test for values that are divisible by 3 or 5.

Checking for Divisible By Using Modulus

Does anyone remember modulus? I remember learning about it in C++, then never using it again as most of my work with JS happens in the DOM, timing things and checking for very simple conditions.

However, modulus is a useful operator. It exists to return the remainder in a division question. It’s incredibly useful when we want to find out if something is divisible by something else, or if it will return a different number. When I was learning about modulus in Baby’s First C++ course, it was being used to make randomization a little more interesting. In this case, we’re going to use modulus to check for remainders of 3 or 5. Here’s what the code looks like now:

for (var i = 0; i <= 100; i++) {

var divByThree = i % 3 === 0;
var divByFive = i % 5 === 0;

console.log(i);

}

That’s not going to do anything different than the previous version in terms of output. But it does add an extra feature to our code. What we’re doing with the divByThree and divByFive variables is we’re checking i (the number we’re looping through) to determine if it’s completely divisible by 3 or 5. Here’s a step-through of one of those statements:

Let’s say we’re looking at divByFive. Here it is:

var divByFive = i % 5 === 0;

So what is it doing? First, we’re creating a variable called divByFive. Then we’re setting it to equal i. The i in this case represents the value that is being fed through the loop. Note that these two variables were declared inside of the for loop where i was already established.

I’m using % on i and then a number, in this case 5, to tell JS to divide whatever number i happens to be by 5 and return the modulus to me. Finally, I check the modulus using === 0 to determine if it’s 0 or not. If it’s not zero then the number in i wasn’t divisible by 5. If it does return 0 then there are no remainders from the division operation and the number in i was divisible by 5. If we had our console.log()s in place, we would then we logging Buzz to the console. So let’s finish that off now, shall we?

Logging Out Fizz, Buzz, FizzBuzz

We need to write an if statement now to determine when to log out a number, Fizz, Buzz or FizzBuzz. The way I do if statements is by determining the most overarching or most strict condition first. This way, I get the most complicated condition out of the way so the else if and else statements don’t have to work as hard. In a FizzBuzz, the most complicated condition to me is checking if a number is both divisible by 3 and by 5. So I’m going to write that first and get it out of the way:

for (var i = 0; i <=100; i++) {
var divByThree = i % 3 === 0;
var divByFive = i % 5 === 0;
if (divByThree && divByFive) {
console.log("FizzBuzz");

} else {
console.log(i);
}

}

In the above code, I’m checking divByThree and divByFive using my new if statement. Remember in the previous section when we wrote those two variable statements and what they would return? After getting through the modulus, we should either have a 0 or any number that isn’t 0 from either one of them. So my if statement starts off by checking to see if i is 0 for both divByThree and divByFive. If it is, then we log out FizzBuzz because we can presume that the number is divisible by both 3 and 5 since there wasn’t a remainder returned for either of the statements.

Next, let’s write out the other two statments to check for divisible by 3 and divisible by 5. After doing this, we’ve also essentially solved the FizzBuzz test:

for (var i = 0; i <=100; i++) {
var divByThree = i % 3 === 0;
var divByFive = i % 5 === 0;

if (divByThree && divByFive) {
console.log("FizzBuzz");
} else if (divByThree) {

console.log("Fizz");
} else if (divByFive) {
console.log("Buzz");

} else {
console.log(i);
}

}

Similar to our first if statement, our else if statements that were just added are checking if i is equal to 0 for our two variables individually. If it discovers either one returns 0 as it loops through 1 – 100, then it returns either Fizz for divisible by 3, or Buzz for divisible by 5. If the number isn’t divisible by 3, 5 or both. Then our else statement takes over and simply logs the number to the console instead. Go ahead and run that and it should evaluate.

Resources

The FizzBuzz Test on C2
Multiple solutions to FizzBuzz including a good explanation of what the test is and why it’s implemented.

Why Can’t Programmers…Program?
Great article that brings to light some problems encountered during programming interviews.

Getting Hired
Information about getting hired as a programmer.



Bonfire: Caesar’s Cipher Solution

Caesar's Cipher

I had to take a little break and do a pen review in between some projects, but I’m back and ready to polish off these beginner’s algorithms. Today, we’re tackling the Caesar’s Cipher Bonfire and the last of the beginner challenges that Free Code Camp has for us. Let’s take a look at what they give us right out of the gate:

function rot13(str) { // LBH QVQ VG!
 
  return str;
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

I don’t even know what I’m looking at here. So before we even try to look into solving this, let’s go over what exactly a Caesar’s Cipher is.

Ciphers, It’s More Than a Cool Word

Way back in time when Julius Caesar was still around, he’d use a cipher to send coded messages to his generals. They have apparently named this cipher after him. Caesar’s Cipher is also know as a Shift Cipher, where the letters are shifted based upon a number. So if you had a coded message like “fvmrk tmdde”, where the key is 4. Then to decode the message, you would have to move the letters back by four to decipher it. In this case, “fvmrk tmdde” deciphers into “bring pizza”, where the letter F, walked back four times, in the English alphabet, is the letter B. And so on for the rest of the characters until we get our secret message. By the way, bringing pizza is a very considerate thing to do when you’re going to a party.

Now, a Caesar’s Cipher might be pretty cool if we were still in grade school and secretly passing notes to each other that we don’t want the teacher to understand, but this type of rudimentary cipher is no longer very useful on a security standpoint. Still, it makes for a challenging and, probably, engaging Bonfire.

Free Code Camp’s Bonfire wants us to decode the above messages, and it gives us a big hint by mentioning the ROT13 Cipher, which shifts letters by 13 places. I’m going to assume that ROT stands for Rotate or some similar word. So we already know our key in this instance, we need to shift these letters around by 13 places each in order to decode the secret message and get our club rings. Let’s get to it then!

Approaching the Problem

  1. The Bonfire has already relieved us of having to do anything roundabout by telling us all the characters will be uppercase, no numbers or special characters we have to deal with. So at least we don’t have to fuss with regex.
  2. The Bonfire has also given us a big hint and told us basically that the key is 13. This eliminates the need for us to search for the key, and it ultimately saves us a ton of time and coding too.
  3. I need to determine if we’re walking forward or backward by 13 places. I am assuming that it is backward. What I did was write out the code, then test it going forward to see if I would get gibberish or not, if I did, I’d walk it back 13 instead. Not exactly the best way to figure out which way a key is going but, it works for what we’re doing here.
  4. Given that we need an alphabet or a coding system to work on, the most straightforward solution would be to create an array containing all the characters in the alphabet, but it’s hardly the most efficient. We’re going to do this using the ASCII table instead to avoid having to fall back on unicode or manually typing up an alphabet.
  5. We know that each character needs to be walked back by 13 characters to decipher things so we’ll have to create a loop that does this for each of the characters in the cipher.

This Caesar’s Cipher Bonfire is actually more complicated than it looks in my opinion and I had to really heavily reference an external source: Self-Taught JS, and it’s a pretty good way to end this Beginner’s Bonfire series before throwing us screaming into our next challenge. I will say it was definitely a mental exercise for a purely Front-End Dev. So I guess I’ll start at the top and go easy.

The For Loop Framework

I already know that I’m going to be working with an ASCII table, but there’s a couple of things I want to do first before I dive into that mess. I know I want to fill an array with the deciphered message. So the first thing I’m going to do is declare an empty array called deciphered to fill up later on. Next, I create a simple for loop that will step through each character that’s fed into the rot13() function. Here’s what I ended up:

function rot13(str) { // LBH QVQ VG!

    var deciphered = [];
    for (var i = 0; i < str.length; i++) {

    }

    return str;

}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

Really easy and straight forward so far. Nothing should be scary to us at the moment, so let’s go on to the next step. I’m going to be looking into three things we haven’t seen yet when dealing with these Bonfires, they are charCodeAt(), fromCharCode() & the ASCII Character index. I’m not going to go into anything too deep with these, but they need to be understood before we can venture forth. Let’s start with the ASCII Table.

ASCII Characters

I’m sure you’ve heard of ASCII, and those of us who were poodling around the internet in the 90s have likely created some ASCII “art” out of these characters in text editors and forum posts. I remember ROFLCopter quote fondly. Also Lollerskates. Anyway…

ASCII stands for the American Standard Code for Information Interchange. What exactly is it anyway? ASCII is one of the most popular formats for text files on computers. This is a format where each alphanumeric character could be represented by a binary number (a series of 0s and 1s, typically seven of them represent an ASCII character). There were a total of 128 characters possible in ASCII and our trusty uppercase letters that we’ll be using for this Bonfire are among them. Wikipedia has a very thorough article about ASCII along with a helpful chart.

The chart is split into a number of columns, each representing a character. You have the binary numbering which is typically seven characters in 0s and 1s. You have an Octal number, a Decimal number, a Hex and finally, the Glyph which represents the characters we’re most familiar with. For this Bonfire, we’ll be using the Decimal number to reference the Glyphs, or capital letters.

Without making you do the math, our capital A is 65 and capital Z is 90. All the characters in between fall in order between those two characters, for example, Q is 81. So we now know the range we can use to evaluate and decipher our alphabet: 65 to 90.

Exploring charCodeAt()

charCodeAt() is a method that returns an integer between 0 and 65535 which corresponds to UTF-16 encoding. Without getting too deep into it, what we need to know is that the first 128 returns correspond to the 128 ASCII glyphs’ decimal number. This means we can use charCodeAt() to determine what number each of the characters in our coded message falls on and since we now have a number instead of a character, we can use that to walk back or forth to decode the cipher.

Here’s an example of charCodeAt() in action:

var sentence = "A great gray dane";
console.log(sentence.charCodeAt(4));

logs: 101

Oh boy, 101. If we look that up in our handy ASCII chart, 101 is the lowercase letter “e”, and that just so happens to be the e in our string: “a great gray dane”. Here’s another example of charCodeAt() in action, this time we’re going to walk it forward by 5 characters:

var sentence = "A great gray dane";
console.log(sentence.charCodeAt(4)+5);

logs: 105

Yeah, we just did basic arithmetic, but 105 is the lowercase character for “i”, and if it can walk us forward by 5, it can help us with our Caesar’s Cipher Bonfire by allowing us to walk forward 13 characters. Here’s charCodeAt() at work again, this time with an entire string of characters. So we’re converting our little sentence into an array containing ASCII Decimals:

var sentence = "A great gray dane";
var convert = [];
for (var i = 0; i < sentence.length; i++) {
convert.push(sentence.charCodeAt(i));
console.log(convert);
}

logs: [65, 32, 103, 114, 101, 97, 116, 32, 103, 114, 97, 121, 32, 100, 97, 110, 101]

So that’s all set, right? We got an understanding of ASCII and charCodeAt() will let us move around in the ASCII table. Theoretically, we can use these two concepts to solve our problem and move on with our lives. Not so fast though, there’s still the problem of converting back to characters from the decimals in our ASCII table. This is where fromCharCode() comes in handy.

Looking Into fromCharCode()

fromCharCode() takes a unicode number and converts it back to a character or glyph, it operates on the same order and numbers that correspond to the 128 characters in ASCII. This is exactly what we’re looking for because up until now, we’ve been converting our letters into numbers.

And now when we convert those decimals back into characters using our glyphs, we want to use fromCharCode(), which looks like this:

var sentence = "A great gray dane";
var convert = [];
var reconvert = [];

// Loops through sentence and changes each character into a decimal ASCII value.
for (var i = 0; i < sentence.length; i++) {
convert.push(sentence.charCodeAt(i));
}
console.log(convert);

// Loops through convert[] and changes its decimal ASCII places into characters using fromCharCode().
for (var j = 0; j < convert.length; j++) {
reconvert.push(String.fromCharCode(convert[j]));
}

console.log(reconvert);

logs: [65, 32, 103, 114, 101, 97, 116, 32, 103, 114, 97, 121, 32, 100, 97, 110, 101]
[“A”, ” “, “g”, “r”, “e”, “a”, “t”, ” “, “g”, “r”, “a”, “y”, ” “, “d”, “a”, “n”, “e”]

Awesome, converted and reconverted again. Now, we can go on to clean that array up and turn it back into a string using join(), something we’ve looked at before in a previous Bonfire (Title Case a Sentence) to get that array back into a more readable string, but that’s the easier part. Now that we know about these three parts, let’s construct our solution for the Caesar’s Cipher Bonfire.

The First Conditional and Loop

Let’s take what we had before and start working out our first loop. In case you missed it, we’re looking at only converting and deciphering things using the capital letters portion of the ASCII table. Capital A is 65 and Capital Z is 90. So I know that whatever I check will have to fall within that range of 65 – 90. I’m going to start pushing values to my empty deciphered array immediately as I check and roll back the letters so what I want is an if statement nested inside of my for loop. Here’s what that’s going to look like:

function rot13(str) { // LBH QVQ VG!

    var deciphered = [];
    for (var i = 0; i < str.length; i++) { if ((str.charCodeAt(i) >= 65) && (str.charCodeAt(i) <= 90)) {
                deciphered.push(String.fromCharCode(90 + str.charCodeAt(i) - 65 - 12));
            } else {
                deciphered.push(String.fromCharCode(str.charCodeAt(i)));
            }
    }

    return deciphered.join('');

}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

Now, this looks all fine and dandy from first glance, but if we really take a look at it, it’s missing a couple of critical pieces. I’m going to go ahead and explain what it’s doing now though, even though it isn’t a fully working solution yet. What we’ve got up there is an if statement that checks str (the encoded message) to make sure that whatever we do to it, it always falls within our range of 65 and 90. When it verifies that, it runs a push() method on our empty deciphered array to ensure that each character it deciphers by rolling things back that it remains in that range by wrapping the decimals around. So for example, if rolling back a character takes it down to 64, the code will force it to wrap around to 90 instead of letting it fall to the ASCII character at the 64 decimal position. Otherwise, we just push the character code into our array just to be on the safe side. This chunk you see above is all for wrapping safety, and it was all written to make sure we never fall outside of our desired range of 65 – 90.

If you ran the above code, you’ll notice only a few select characters get decoded. These are mostly the characters that end up wrapping around. So at least we got those dealt with. Let’s finish this up and start rolling back the characters that don’t wrap around.

The Caesar’s Cipher Solution

Having built in the range safety above, I’m going to actually push characters now using the rot13 key. We want to nest the above if conditional in another if conditional that will check and roll back the characters by 13 places. Here’s what that will look like:

function rot13(str) { // LBH QVQ VG!

    var deciphered = [];
    for (var i = 0; i < str.length; i++) {

        if (str.charCodeAt(i) - 13 < 65) { if ((str.charCodeAt(i) >= 65) && (str.charCodeAt(i) <= 90)) {
                deciphered.push(String.fromCharCode(90 + str.charCodeAt(i) - 65 - 12));
            } else {
                deciphered.push(String.fromCharCode(str.charCodeAt(i)));

            }
        } else {
            deciphered.push(String.fromCharCode(str.charCodeAt(i) - 13));
        }

    }

    return deciphered.join('');

}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

In the above code, we have an if statement added above our previous conditional. That if statement checks whatever character we want to roll back to see if it will be less than 65. If that evaluates to true (where a character is less than 65), it falls into the if conditional inside that checks to make sure the character stays in the 65 – 90 range, if it does, we initial the code roll the character back while forcing it to remain within range. Now if our exterior if conditional returns false, it falls into the external else statement that will simply roll our characters back by 13 places. Each of these evaluations and rollbacks are done within a push() method that adds the resulting values to the deciphered array.

By the end of the function, we return a deciphered array connected to a join() method so it results in a tidy looking string. Put that in and evaluate it and it should pass the Caesar’s Cipher Bonfire. Phew, that was a long one. This is far from the most elegant solution to this Bonfire, so feel free to share your solutions in the comments!

Glad to have gotten that one done. Between how busy I’ve been and how hard this one was for me, I’ll be glad to be moving on to the next Javascript challenge. This series isn’t going to end here. After all, we still have the Intermediate and Advanced Algorithms and Bonfires to work through. But I do plan on going back and covering some more basic Javascript and programming basics while simultaneously addressing the Intermediate Bonfires. So I hope to see you there!

Resources

Self Taught JS, Rot13 Caesar Cipher
Invaluable resource that heavily inspired the solution I came up with for this Bonfire.

Coding Tutorials 360, Caesar’s Cipher
A different approach to solving the Caesar’s Cipher, using a written out alphabet instead of messing with ASCII.

Unicode Solution for Caesar’s Cipher
A really pretty looking (can code be pretty?) solution using Unicode.

Allure Solutions, Caesar’s Cipher
A very similar solution to mine, written a little more cleanly. There are some great alternatives and modifications in the comments to check out too.



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: Truncate a String Solution

Truncate a String

FreeCodeCamp’s Bonfire wants us to truncate a string this time. To truncate something would mean to cut off a string by a certain amount of characters. It’s been a busy few weeks so I haven’t had time until now to dig into this and post it. But here we are, working with strings again.

Truncating isn’t the same thing as abbreviating or creating an acronym. It is, quite literally, you cutting off a string at a certain point in the character count. Truncation occurs on this blog, and many others, as a way of shortening pages and allowing users a small glimpse of the content before they commit to clicking on something to read or view the rest. So let’s see what FreeCodeCamp has given us:

function truncate(str, num) {
  // Clear out that junk in your trunk
  return str;
}

truncate("A-tisket a-tasket A green and yellow basket", 11);

The Bonfire gives us a hint that we may have to use the slice() method. We’ve already used slice(), it essentially allows us to take certain parts of a string. If you need a refresher, slice() was discussed in our Title Case a Sentence Bonfire Solution. Let’s talk out our approach.

Approaching the Problem

  1. Truncate() needs to be able to read in the str and num provided by the arguments and use num to determine how much to truncate. We can do this by evaluating the length of str, by using length.
  2. We have to find a way to weed out a couple of caveats, first what happens if num is larger than str? We shouldn’t have to truncate anything in that instance.
  3. Since the Bonfire expects us to add ellipsis at the end of our truncated string, we’ll have to evaluate to make sure that when num is less than or equal to three (or the characters a plain-text ellipses takes up), str gets truncated by num and appended with an ellipses at the end.
  4. Finally, we need to determine how to truncate a string when it is both larger than the num and when num is greater than three. At which point, we should apply slice() to it using num as the argument minus 3 to allow for the ellipses. Then append an ellipses onto the end.

I know that was a little confusing to suss out, so here it is in a step-by-step format:

Step 1: Truncate() takes in str and num as arguments.
Step 2: Truncate() evaluates to see if the total length of str is less than or equal to num. If it is, no truncation needs to take place because str is already too short to truncate. If str evaluates to be less than or equal to num, then str is returned and no truncation takes place.
Step 3: Truncate() evaluates if num is less than or equal to 3. If it is, then str is sliced starting at 0 and using num as an indicator of where to stop slicing. It then adds an ellipses to the end of str and returned.
Step 4: Truncate() assumes that if the previous two conditions are false, it should truncate str by using slice().

The Solution to Truncate a String

function truncate(str, num) {
  
  if (str.length <= num) {
    return str;
  } else if (num <= 3){
    return str.slice(0, num) + '...';
  } else {
    
    return str.slice(0, num - 3) + '...';
  }    
}

truncate("A-tisket a-tasket A green and yellow basket", 11);

The above solution is running an if/else if/else statement to check various scenarios and using slice() as a means to truncate the strings that the Bonfire throws at us. It falls into the first if statement that evaluates the length of string, if string is shorter or equal to number, then no truncation is necessary.

The if statement continues into the else if condition where number is evaluated to see if it is less than or equal to 3. If it evaluates to true then string is sliced starting at the 0 position in the string, and ending at a digit equal to num. Then we append the returned string with an ellipses.

Finally, our last else conditional catches all other scenarios where it slices string starting at the 0 point and uses num minus 3 and appends an ellipses at the end. Send that in and it should validate. Hooray, truncation!

Resources

FCC, Bonfire Truncate String Solution
A nice alternative using substring() as an alternative approach to truncate a string. A little less coding involved with this one too.



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.