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.



CSS Font Weights Explained

Those not too hip with typography might at one point wonder, “Why are the font weights on a ranking scale from 100 to 900?” Where are those numbers coming from? It was actually an interesting questions brought up to me recently that I hadn’t thought much of. After all, no one’s breaking the internet over not knowing why font-weight can take a numerical value from 0 to 900 and why anyone would want to use the numerical scale over the (arguably) more intuitive, lighter, normal, bold, bolder scale.

There are a surprising, delightful and numerous amount of things about CSS that harkens back to design theory and borrows from typography principles and font-weight’s number system is a pale echo of a type family’s numbering system. Before I get to explaining the numbers, we have to explore a few terms related to typography first.

A type family (or font-family as far as CSS properties go) is a typeface and all of its total variants. Where you might have Helvetica identified as a type family. Inside that family you’ll have members like Helvetica Roman, Helvetica Italic, Helvetica Bold.

Variants within a type family are different styles of that same typeface. For example, the Italics for a typeface is an example of a variant. Small caps style within a type family is another example of a variant. Within CSS, we declare different variants for our font-families by using font-variant.

Weights within a type family are generally considered how thick or thin a typeface appears. On the lowest end of the scale, you have the thinnest of thin characters. On the other side, you have big, bold and thick characters. As you’ve probably guessed by now, font-weight is what you generally use to affect the weight of your web typefaces. And it is with font-weight that we’re going to dive into the numbering system.

The Typography Numbering System

Most large type families have a numbering system that dates back to some of the earliest examples of variant and weight-rich typefaces such as Univers and Helvetica. These typefaces typically have family members that run the gamut of thick, thin, condensed, wide, and so on. So a type numbering system was devised to easily catalog and describe the various members of–let’s say, Univers. Where you could say, Univers Normal, you could also say Universe 430. Why does 430 mean normal?

  1. The first digit identifies the weight of a typeface.
  2. The second digit identifies its amount of compression (ex. condensed, ultrawide, etc).
  3. The third digit signifies the stance (roman or italic).

Typically in the numbering system, 400 is identified as “normal” weight, 30 signifies normal compression, and 0 would mean that the typeface is roman or upright. So that is what we mean by Univers 430. It is of the type family, Universe. It is normal in weight, normal in compression and upright roman in stance.

Another example might be Times New Roman 631. This would mean a Bold and Italic Times New Roman. 600 typically represents bold, 30 would indicate normal compression and the 1 identifies it as an italic variant.

Last example, Helvetica 620. This is Helvetica bold, upright and condensed. The 600 indicates Bold, the 2 is meant to represent condensed, and the 0 identifies this as an upright variant.

So that’s the typography numbering system in a nutshell. Many designers typically prefer to identify the typefaces by name–because many of us are not creatures particularly fond of nondescript numbering systems. I don’t blame you, I’m not hip on it most of the time either. But even I have to admit to its simplified, condensed elegance. However, it should be more obvious now how and where font-weight gets its numbers and considering how many web fonts have large swaths of weights, why not keep in mind what the numbers mean?

100 – The lightest of the light.
200 – Light.
300 – Book.
400 – Normal.
500 – Semibold.
600 – Bold.
700 – Extra Bold.
800 – Ultra Bold.
900 – Black.

Maybe some day CSS spec will catch up to the type family numbering system and we’ll be declaring our font-families as Proxima Nova 431. For more fabulous insights on typography as well as a quick and useful read about typefaces, check out Erik Spiekermann and E.M. Ginger’s, Stop Stealing Sheep & Find Out How Type Works (2nd Edition).

Resources

Fontfeed, It’s All in the (Type) Family
Great resource that showcases a more visual chart of the original font numbering system with Univers’ two digit example. Also takes a jab at Helvetica and I’m always for a bit of that.



Should I Learn Javascript or jQuery First?

This has been a debate raging all over the development world with a lot of heated conversations opposing or promoting one or the other side. I wanted to put my thoughts down somewhere and since this is my blog, why not?

I’m of the opinion that before you can determine which you should learn first, you need to figure out why you want to learn either language to begin with. Are you interested in being more of a developer or more of a designer? Is your end goal to make a website, or a web application? And how much of your heart is into the code versus the design aspect?

I’m not going to say, everyone needs to learn jQuery first. Or everybody needs the fundamentals that comes from learning Javascript. What I do question is pushing people who are more interested in getting things done quickly from a design standpoint into learning Javascript when the vast majority of the time, they aren’t going to use many of its powerful features.

Learn jQuery First

I advocate some people learn jQuery before they get to Javascript. This doesn’t mean that people who learn jQuery have spoiled themselves and they’ll never catch on to JS. If someone wanted to figure JS out anyway, they would do so whether they start with the Library or the language itself. I tend to recommend those who are looking to do quick, simple things to make good looking designs with nice effects and some functionality aim for jQuery first. It’s faster, it’s easier, it doesn’t force you to mire yourself in a bog of complex programming logic before you can do a lot of really cool things with it. And some people actually find that learning jQuery first opens up a level of understanding that would have taken them much longer to grasp had they struggled through the JS route first.

Learn Javascript First

Javascript is the foundation. It’s like the base that you need to understand if you wanted to do more complex, more intricate things with the language. People who go into jQuery first need to be clear that they’re learning shortcuts and that there’s a lot more than just what they see on the surface. Javascript first can be intimidating, especially to people new to coding. But it’s the kind of language that lends itself well to helping you understand even more complicated languages once you have a grasp of it. A lot of developers recommend going the JS route first. After all, you need to crawl before you can run, and ultimately starting hard and moving to something easier is how some people learn best.

Ultimately, it boils down to what your goal is. Are you content to know enough to make some cool effects happen on a website? Great. jQuery first. And if you develop a love for the language, Javascript is always there, lurking under the sand and just waiting for you to dig in.

If you’re more into development than design, then you know you need to start on the more complex side of things. Shortcuts in jQuery are lifesavers, but good developers usually learn it the hard way before they figure the shortcuts out. This is so they understand the fundamentals and those fundamentals can then be translated to other languages, something jQuery just isn’t as good at.

Long story short, if you’re focused on design, go with jQuery first and upgrade later. If you’re focused on development, go with Javascript first and figure the shortcuts out after you have the foundations down. Those are my thoughts on it. What do you think?

For me, personally, I learned Javascript first because I wasn’t really given a choice. We sat down in class one day and were told that Javascript was what we were going to learn. We didn’t get too far, the basics were all. Enough to give us the fundamentals that are relevant no matter what language I move on to. One year after that class, the first version of jQuery came out.



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().



WordPress Visual Page Builders

Visual page builders for WordPress sites have gotten some attention lately because they can make building a site out very easy–especially for those who don’t know code. You still need a developer to get certain functionality working, but a page builder can definitely get you up and running with a semi-custom site.

The following is a list of WordPress page builders that I’ve encountered.

Visual Composer
Massive following for WP Bakery’s Visual Composer and a favorite of mine for sites where a client wants to be able to update and adjust the design themselves. If you’re just someone looking for a drag and drop page builder, VC has a lot of powerful features and options to chose from. If you’re a developer looking to allow clients the ability to edit their own pages, and want something that will work well with or without a framework, VC is a good option. It’s not a free solution, but at $34, you are getting your money’s worth.

VelocityPage
A rapidly increasing user base around VelocityPage and for good reason. It’s a feature-rich page builder that offers even more user friendliness than Visual Composer. It’s also highly compatible with existing, pre-made themes and runs out of the box on a blank theme just fine. VelocityPage starts at $97 for a single site. I’m looking into using VelocityPage as an alternative to Visual Composer for some clients because its workflow is a bit more simple.

Page Builder
One of the free options for a page builder is, simply named, Page Builder by Site Origins. It has a nice feature set with a good sized following. It might not be as feature rich as VC or Velocity Page, but it has good community support and if you’re a dev looking for a page builder for your client that doesn’t have bulky extra bells and whistles, Page Builder is worth looking into.

Divi Builder
Another free option (you need an account to get it) is the Divi Builder, used by Elegant Themes and featuring some nice options to get your site up and running quickly and easily. It isn’t as powerful as VC or VelocityPages, but it handles simple sites like a champ. One of the nice features in Divi is the ability to save segments or components that you’ve built to quickly insert into other pages. Then edit those saved segments and have the changes reflected on all pages that they appear on. It’s a major time saver.

Themify Builder
A premium page builder with a lot of nice features, on par with VC and VelocityPage when it comes to extras and support for things such as WooCommerce. Clocks in at $39 and has some really nice parallax options built in. If you don’t see it, there’s always the add ons which has some useful features to extend your vanilla Themify Builder.

I’m still of the opinion that you need a designer to lay out a good, presentable design with optimized content and architecture whether you’re using a page builder or not. And you still need a developer to create a fully customized option that the page builders can never automate. Things like optimal user flow, accessibility and dependencies are still very much in the human domain and can’t be replaced by page builders. What page builders excel at is allowing a non-coding user to create something quick out-of-the-box. When your business grows beyond its first stepping stones, or if you want to start off a business with a good foundation, call in the designer and developer.



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.



Resources for Checking Accessibility

Making websites and apps that work for everyone should be something every web designer thinks about. It’s been on my mind a lot lately because I’m working on a project that must be Section 508 compliant. I’ve found the following resources useful.

Easy Checks for Accessibility
Gives some generalized tips and tricks for ensuring accessibility for websites. This isn’t a tool, but a great resources to brush up on some of the simpler things about making sites that can be forgotten as our development and design processes become more involved.

Check My Colors
Pretty cool site where you can plug in any live URL and get an analysis back on how your site does when it comes to color-related contrast.

Readability Test Tool
Tests the readability of your text as it relates to your diction, sentences and so on. The more readable something is, the more people will be able to understand it. FYI, this website’s readability is around Grade 7. I’m not writing the next greatest novel of our time, so I’m pretty happy with that.

Contrast Ratio
Way cool tool to check color codes against contrast. It gives you a live score of how your color choice will perform.

Colorblind Filter
Tests your website against color blindness filters. Renders an “as close as possible” version of your site as someone colorblind might see it. Very useful for making sure no one misses out on critical information that you may have chosen to color code.

While these tools are useful and kind of neat to play around with, keep in mind that if you’re working with something that must be accessible, a human should be the final point of reference for all accessibility evaluations. Software, at the moment, can’t catch it all, but it can help us out a little here and there.

Resources

Usability Geek, 10 Free Web-Based Accessibility Tools
Web Field Manual



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.



Great Places to Get Free Images

Stock photography can make or break a design–whether it’s a website, app or print piece that you’re working on. Good stock photography often comes with a hefty price tag. But, when you’re a design student, buying thousands of dollars worth of stock photos might not be a realistic expectation. So any time you can get some nice free images, is a good time. I would have loved to have had access to some of these sites in college. Check out some of my favorite free image resources and save some money.

The British Library on Flickr
Tons and tons of old school illustrations and photos from the British Library. I can imagine having a hard time figuring out what to do with some of these images, but the collection is no doubt extremely impressive. And if you’re working on a vintage project, this might very well be an invaluable resource.

Pixabay
A giant collection of stock photos, and a decent collection of photos featuring people in them. One of the more difficult parts of sourcing free stock photography is finding images containing people. Pixabay’s taken the legwork out of that and sourced a few good quality images so you don’t have to worry about finding an image of a–oh, I don’t know–woman biting into a doughnut while a small green arm comes out of her nostril. Look, I just find these things. I can’t explain them.

Unsplash
My favorite place on the internet–when it comes to free photography anyway. Unsplash’s images are gorgeous, well-curated and new photos are added every ten days. They have a simple licensing structure too, it’s literally: Do whatever. Some of the images on Pixabay come from this fabulous site.

StockSnap.io
Tons of beautiful copyright-free photos here and they’re all very searchable and of good quality. Stocksnap borrows from UnSplash and KaboomPics, but consolidating those two resources makes things a little bit easier for stock photo searchers. I’ve found they have a rather impressive array of really nice food-related photos.

KaboomPics
Excellent photos, lots of good quality images and you can use them personally and commercially, with some very reasonable restrictions (you can’t resell them, you can redistribute them without asking first, etc). I’ve used some of these images myself when building generic themes to fill out photo galleries, blog posts and other dummy content.

FancyCrave
Beautiful, free stock photos. Lots of artistic shots with a lot of very usable content. Bonus points to FancyCrave for updating their library daily!

Gratisography
One can thank Ryan McGuire for curating this fantastic website full of free photography. Beautifully shot, some with a bit of photo manipulation applied. It would be super awesome to donate a few bucks for the work McGuire does. And you know that green arm doughnut picture? It came from here.

New Old Stock
Need some pictures, but you need them to be vintage? Old New Stock has you covered. No attribution or worries about copyright, just a lot of really fascinating imagery for free. If you’re a Shorpy fan, definitely check this one out.

Startup Stock Photos
If you ever needed photos of people in an office, working on laptops, sitting in meetings, contemplating UX, and just generally doing their jobs during a workday in the office–Startup Stock Photos is probably your place. They also have some great shots of equipment and devices.

Made in Moments, Freebies
I’ve always wished my husband and I could travel the world, freelancing wherever we land–maybe some day. In the mean time, living vicariously through Tomy & Marina’s collection of free pictures will have to do for now. They do have paid photo packs, but check out the freebies section I linked, plenty of good content there.

Albumarium
Another collection of stock photos from various sources. Presented nicely, and with a search function which is always appreciated.

ISO Republic
Some of the nicest architectural photos I’ve seen from a free stock site. I love the repeating patterns that they’ve captured and there’s a very unique perspective to each of the shots on this site.

With so many great stock photo resources, you should be able to find what you need without spending too much. Some of these photos work fantastically for dummy content in a theme as well. Or as blog post images too. Enjoy!



Bonfire: Check for Palindromes Solution

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

Approaching the Problem

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

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

palindrome("eye");

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

racecar = racecar
eye = eye
tacocat = tacocat

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

abutttuba = abutttuba

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

deerrun = nurreed
hockey = yekcoh

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

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

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

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

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

Checking for Palindromes Using Existing Methods

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

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

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

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

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

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

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

Now probably looks more like: degasarewenotdrawnonwardnoinuniondrawnonwardtonewerasaged

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

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

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

degasarewenotdrawnonwardnoinuniondrawnonwardtonewerasaged

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

Checking for Palindromes With a For Loop

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

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

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

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

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

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

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

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

Here is a partial step through as I understand it:

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

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

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

Subtract 1 from stripStr.charAt(end)

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

A Faulty Sidetrack

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

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

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

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

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

That means our updated solution would look like this:

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

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

Resources

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

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

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

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



The Benefits of Managed WordPress Hosting

If you don’t plan on digging too deep into server management and all you need to do is host a WordPress site, you can’t go wrong with either of these fine folks.

WPEngine
Starts at $29/month. WPEngine is a solid hosting solution that at least two of my clients have used in the past. They have an excellent reputation as being one of the fastest and most reliable WP dedicated hosts out there. And well worth the monthly fee for the peace of mind, expertise and speed that they deliver.

Flywheel
Starts at $15/month. Flywheel is speedy, has great up times and also offers peace of mind backups and security. All of it backed up with a friendly small team of professionals.

I know some clients have balked at the prices they see  attached to these hosts compared to their features. After all, a standard shared host can offer them unlimited space, unlimited bandwidth, and all for $5 or less a month in many cases. Why on earth shell out $15 or more a month for hosting? Is WordPress hosting really that much different than a regular website? So let’s look at this from the start.

Is Hosting a WordPress Website Different Than a Regular Website?

In some ways, yes. WordPress is a Content Management System (CMS) built with PHP and using a MySQL Database. While most small websites do perfectly fine running WordPress on a shared host, many people interested in running WordPress rarely have a 5 page site to only use the backend to update text once in a while. Chances are pretty good that the reason most clients who went with WordPress do it for its blogging capabilities, social media extensions, eCommerce options, scheduling, database, and on and on. What I’m getting at is, the vast majority of people running WordPress websites aren’t content with five static pages.

If they’re updating a blog often, running an eCommerce store or really anything that sends data and retrieves data from the MySQL database on a regular basis, you are relying on the server to receive those messages and send back the necessary data. The more calls you make to the server, the slower your website is to load and perform functions because it has to send the message to the server and wait for the server to get back to it.

Now, we all know that the more people sitting on the same server, the slower the website tends to be. After all, those people are all running sites too. Some of them static HTML/CSS, but with more and more businesses running WordPress sites, server loads are going up as more websites send and receive data using server resources.

This is where a dedicated WordPress host such as Flywheel and WPEngine come into play. They’ve optimized for these types of scenarios, server messages get received faster and are sent back faster as a result. This means your site loads quickly, freakishly quick. The kind of quick massive companies spend tens of thousands a year to accomplish with much more expensive and expansive server architecture.

So bottom line, is hosting a WordPress site different from a regular site? Yes, especially if you’re using the Database a lot. How much faster is WPEngine or Flywheel than a regular host? Oliver Nielson from WebMatros.com did a comparison between the major WordPress Hosts versus a very well-respected general host–MediaTemple. And the results are pretty telling. Check them out.

 Is WordPress Security Really That Much of a Problem?

No, but that’s if you know what you’re doing. Hire a developer who knows what they’re doing. And you consistently follow the developer’s recommendations and advice regarding security of your own site. That’s a lot of “ifs” and what I encounter is that clients often drop their website maintenance shortly after deployment. They can hardly be blamed, clients should be focusing on their business not worrying over their website. There are the basics of keeping a WordPress site safe:

1) Keep your WordPress Core up to date.
2) Keep your plugins up to date.
3) Don’t use a theme or plugin that you’re unsure of in terms of quality.
4) Uninstall and replace all outdated or unsupported plugins.
5) Keep strong passwords and,
6) Avoid being compromised at the local machine level.

It seems like a lot to think about, and I’m not even getting into the what-ifs of spammers or brute force attacks that hammer the login pages in an attempt to suss out your password–and that’s just the predictable stuff. This is really where a dedicated WordPress host comes in handy. They track the security issues for you, they do the backups, they monitor the server, and if something does happen the majority of them can mitigate the damage, stop it before it goes too far and restore your site back to the way it should be. If you’re running eCommerce, or doing anything that handles customer data, it’s worth it to shell out for the peace of mind, in my opinion.

What About Unlimited Space and Bandwidth?

I addressed the unlimited space and bandwidth myth in an earlier post: Choosing a Good Web Host. Chances are pretty good that shared hosts don’t actually mean unlimited space and bandwidth and they’re just using those features to draw in customers, betting that the vast majority of their customers won’t even come close to the limits they actually have in mind. What you get is an upper limit they won’t tell you about, and if you cross over that limit the host might throttle your usage, send you messages about your resource consumption or strongly insist that you upgrade your account.

I rest more easily going with hosts who are upfront about what you’ll get over the ones who either won’t tell you or offer you misleading features and then throttle you back when you actually take advantage of those features. So yes, the two dedicated WP hosts I listed above (and there are other great ones, these are just the two I have experience with) do have limits on what resources you can eat up, but they are disclosing it and not selling pie-in-the-sky unlimited space and bandwidth. You will get exactly what you pay for, you know what you’re paying for, and you know you are guaranteed to be allocated those resources.

Now the capacities are pretty low, and if you want more, you need to be prepared to pay more for it. If the capacity is going to be a problem, I generally bump up to recommending a managed VPS. Everything costs something, unfortunately.

Ultimately, what hosting you or your clients end up on is dependent upon the website, what’s being run on it, and how much the client will expect to pay for hosting. There’s definitely a lot of benefits to going with a dedicated, optimized WordPress server. Peace of mind, simplicity and security features are some of the most attractive reasons.

Resources

Flywheel, Managed WordPress Hosting
WPEngine / Managed WordPress Hosting
Managed WordPress Hosting Pros and Cons, Sitepoint