Author: Khanh



Another Year, Another Redesign

It’s my mind that my website’s design goes through a cycle. Sometimes that cycle lasts only a year, other times it lasts a couple of years. It always starts off with the honeymoon period where everything is great and I love it to bits. Then I fall into the comfortable maintenance period where things are still working, but once in a while something goes a little off-balance and it eventually gets fixed. Then it enters its twilight period where I’m tired of looking at it, and tired of patching all the little things and feel like it would just be a better solution to redo the whole damn thing. This twilight period is usually where I question my value and skills as a designer and developer and it bothers me to no end.

Usually around the end of that second year, I get the uncontrollable urge to redesign this place. In 2017, my website is starting to show its age a little and I’m finding annoying little things here and there that I’ve been meaning to fix for months. Sure, it still works, but sometimes I wish it worked better and as an example of what I do, I’m feeling a bit underwhelmed by the current site.

I’m thinking of going ultra simple this time. Part of the reason for that is because I’m tired of the fancier bits and pieces sometimes going awry on this older browser or that older browser. So, I’m looking to update the layout, fix the code base, simplify or otherwise modernize the design, or maybe just use all this as an excuse to add my latest work to the Portfolio section.

Whatever the reason is, I’ll be working on (in whatever spare time I have) a redesign for Iron Ion which I’m hoping to roll out before the fall season. Outside of musing about it all and one day seeing a completely different looking site, nothing else is going to change.

I’ve got a dozen or so coding posts that I’m still working on, spare time to work on these things is sparse nowadays–not that I’m complaining or planning to stop any time soon. I’m always happy to visit the site and see your wonderfully kind comments and notes. I do read every single one of them, and try to respond to all that I can–even if I don’t have the answers. So thank you for all the comments, questions and feedback. Hopefully before the end of 2017, this place will look a little different so I can assuage the screaming designer in me. 🙂



Developers Should Learn Design, Designers Should Learn to Code

I’ve pondered the question over the entire course of my time working as a freelancer and continue to ponder it to this day: Should developers learn to design? The common advice to designers is that yes, you should learn to code. But what about the other way around? With the recent push to get more coders out into the workforce, we often forget to pull back and think of the simpler things. Such as the question of whether someone who programs should know anything about design. I say, yes. Yes, programmers and developers should know design.

But why? Isn’t it about solving problems? Clean code? Making the engine start, and keeping the gears turning? Sure, that’s a large proportion of a developer’s job. But it’s hardly the only thing. A large portion of a developer’s work–particularly front-end development, is ensuring whatever you make is usable. And usable tends to go pretty well with the idea that everything you make, ought to be well-designed.

So here’s a list, because I love those, of reasons why developers should learn design.

Usability: So many times I’ve seen developer or programmer created applications that were made (and made well) without the end user in consideration. There’s a lot that goes into the usability of a product. It’s very easy for people to forget, as they’re creating something they’re passionate about, that other people will eventually have to use it too. Design is a large part about usability, or UI/UX considerations. So, for a developer to make a highly usable, highly desirable product, something a thing or two about the good design that goes into these products is beneficial.

Possibilities: Just as designers have been told to learn code so they understand what is and is not possible, developers would benefit from learning some design. This is so that they gain a better understanding of what is and is not good user experience.

Teamwork: Working in house or as a freelancer is rarely an entirely independent exercise. You’ll have to talk to the designer eventually, get their opinion on various design choices they’ve made. This is where having an understanding of what they’re talking about when they tell you that you should, ‘increase the leading on the body type to improve the hierarchy of the layout’ is probably a good idea.

Perspective: Since when has having a narrow perspective been a good idea in a professional setting? Broadening your perspective by learning a little bit about another subject makes your work more well-rounded and allows you to approach projects and tasks with a more diverse skill set. I don’t think I’ve ever heard an employer or client say, ‘We want to hire someone who’s only good that this one thing. And if they have any other skills or abilities, then heaven help them, we aren’t giving them the job!’

Presentation: While a developer shouldn’t be tasked to sit down and layout things as their primary job, the fact that presentation is important to a project is difficult to argue with. Aesthetics matter. How something looks is the very first thing people will pay attention to. So if it looks bad, then users have a bad impression of your work–whether or not you spent hundreds of hours writing the most beautiful, clean code you’ve ever written in your life. Chances are pretty good that your users aren’t going into the code to see how you’ve written things to make the program work. But they are going to want to know what the buttons on your interface do, or how to use your menu system.

I come from a perspective shared by fellow designers who have to wear multiple hats. I have always considered myself a designer first and have always accepted that designers should know code. Initially, it was so I could be self-sufficient as a freelancer. Then it turned into a philosophical advantage and finally to the point where I’m now referred to as a developer first. While I still identify primarily as a designer, I often recommend developers look across the pond. The four reasons above are just the start. You may find it fun to learn some design.



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!



Conditional WordPress Redirects

Today, we’re talking about conditional ways to redirect a user in WordPress based upon the page they are using to log in. As with all things I do in WordPress, whenever I get a new challenge that takes me a while, I feel the need to share it. Or at the very least, post it so if I ever need it again, I know where to go and grab it.

The latest challenge came from a client who needed an override for users logging in from one particular page. What was happening before was that all users from being sent to a page from the generalized redirect that was already on her website. I spent hours combing through the code of the site getting increasingly frustrated because how many places can someone hide a redirect? Only to realize within the span of a few seconds that the redirect was not being handled in code–but using a plugin. Augh.

After disabling the redirect handled by plugin, the challenge then became how to properly redirect users to a specific page when they were logging in from another specific page. Now, this could be accomplished through user role set-up and using a redirect plugin, but I balked at the hours of tedious work labeling the users who would use one specific page who needed to just access another specific page that wasn’t going to be handled by the redirect. I knew there had to be a way to detect what page a user was coming from and redirect them accordingly.

The Generalized Redirect

First thing’s first, I had to put the direct back in since I disabled it in the plugin. So here’s the redirect that will send all users logging into the page to a specific page…

function login_redirect( $redirect_to, $request, $user) {
return 'site address here';
}
add_filter('login_redirect', 'login_redirect', 10, 3);

That piece of code up there, when you replace ‘site address here’ with your own URL, will send all users logging into your site using your login form to the specified page.

Conditional Redirect Based on Page

The next step was write a conditional statement that evaluated whether the user was coming from a specific page or not. I relied on a very good StackOverflow answer for this one. You can find the original answer here: Thanks to Dominor Novus on StackOverflow

function login_redirect( $redirect_to, $request, $user ){
  if (stripos($_SERVER['HTTP_REFERER'], 'page-permalink-address') !== false) {
    return 'other site address here';
  } else
    return 'site address here';
  }
add_filter( 'login_redirect', 'login_redirect', 10, 3 );

Up there, you are going in using PHP to detect, within the referring website, if a specific query, name or permalink address exists. If it does exist, then your login redirect will send the user to the other site address. Otherwise, if it does not exist, it will send the user to the original site address using the regular redirect.

All this boils down to using a basic if/else conditional. Where I really needed the help was finding out how to get the page to detect the origin site address. Once that was in there, we were open for business. I hope this write up helps someone else struggling to figure out how to override a redirect without having to set up a complicated user role system and use a redirecting plugin.

 



Salad Shake, Our Food & Drink App!

salad shake

Over a year ago, my husband and I started learning Swift in an effort to make our own app for iOS. Pretty much a year later, we finished Salad Shake, a Food and Drink app for iOS Devices. We learned a lot, and we’re getting ready to launch it on July 11, 2016 to the Apple App Store. It’s been a real roller coaster ride for us. Learning Swift was scary. Then finding out just a few months after getting comfortable with the language that Apple is releasing a new version was also scary. Figuring out how Swift handles data took some patience. Then navigating the Apple Developer Tools to just get the app submitted was an adventure. However, it’s done and is approved for sale on the Apple App Store.

Salad Shake is Launching July 11

The app is called Salad Shake, a unique little thing that suggests things to put in your salad. Salad Shake isn’t online until July 11, 2016. You can check out the landing page I set up for it here: http://saladshake.io

I’m quite proud of what we’ve accomplished. We didn’t use Interface Builder for any portion of it. Coded Salad Shake entirely in Apple’s language, Swift. We even built our own algorithm and I designed and drew pretty much every art and graphical asset in the game. I even have a bunch of freebies you can grab here: Get Some Free Salad Shake Stuff!

Did I mention that I have no video capabilities, put together a preview video using After Effects anyway? You can check out that video here: Salad Shake Preview Video

I’ll be making another post on launch day to give you all the link to Salad Shake on the Apple App Store. In the mean time, we’ve discovered that after overcoming the programming hurdle to actually make the app, the biggest hurdle in this entire process is marketing. While working in design and development of websites is something I’m fairly comfortable with, marketing has always been handled by someone else so I’m learning a lot of things about marketing–primarily that it is really, really hard.

If you run a blog or channel YouTube and you’re interested in featuring or reviewing our app, feel free to get in touch with me using this good ole contact form, or message me on Twitter: @imbriumapps and let me know you’re interested in Salad Shake and I’ll get back to you faster than you can say, “Go” and we’ll set something up.

Salad Shake is a Food & Drink app for iPhone 4s and better, iPad Air and iPad Pro. It will be released on July 11 and will sell for $0.99. No ads in the app, no in-app purchases and no subscription fees.



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.



Custom Page Template WooCommerce Product

I recently had two client projects that required the Single Product WooCommerce page to display differently from other Single Product pages. Normally, your run of the mill single product page would have the product image, cost, description and an add to cart button. My clients wanted theirs to look different, but only for a single product or only within a certain product category.

The solution I have is for one particular product, or a series of categories. It isn’t a fully built plugin, though I assume if someone were to go the extra mile to make a plugin for this, they could save some people a whole lotta time. This is using the (as of this writing) WooCommerce 2.5.5 on the latest version of WordPress 4.4.2. This short write up assumes that you know your way around the WordPress and WooCommerce template files and can make PHP edits without assistance. Without further ado, here’s how you set a custom page template for a WooCommerce product or product category.

The Problem

Normally with a Page, WordPress allows you to assign a specific page template. With this template, you can choose to have a sidebar, or omit it, or even display a completely blank page with only the post contents. However, posts don’t do this by default (though you can accomplish that with this plugin [note: you may have to modify it a bit to work with the latest version of WordPress]) and WooCommerce products definitely did not support this functionality. So, since this wasn’t built into WooCommerce and I didn’t see anything that was pre-created to allow for this functionality, something had to be customized.

1. Copy WooCommerce Files

To force a product to display a different template page than the default, you need to pull two files from WooCommerce. The first file is single-product.php. Single-product.php controls the template files that should be loaded as well as loops through and displays the product information on the screen. You will be editing single-product.php to add an if conditional. The other file you’ll need to pull from WooCommerce is content-single-product.php. This file is your page template itself, it is the file you’re going to edit to make your product display however you want. So in short, you need to grab these two files from the /woocommerce/ folder:

single-product.php
Used to call the templating files that determine what information and how your product page will display the product’s information.

content-single-product.php
Used as the product template, and will be modified to change the product page to display the information or styling that you want.

2. Set Up Your Product/Category

I’m assuming you’ve already used WooCommerce so setting up a product or a product category shouldn’t be anything new. Still, it goes without saying that if you want a product or product category to have a custom page, you should probably have it all set and ready to go.

3. Modify Your Copied WooCommerce Files

With your content-single-product.php file, you’ll want to modify the tail end of it to add whatever your category or product is. I recommend naming it something that you’ll be able to readily identify. So if your product category was something like, “Hats” then append the file name of content-single-product.php to something like this: content-single-product-hats.php. Also in this file, you’ll want to make your template changes, so add a sidebar, remove a sidebar, change the loop, do whatever you want to get it to look the way you want the product/product category to display.

Next, you’ll need to edit some code in single-product.php. Like I said before, this is the file that contains that loop that actually determines what templates to load up to display the products. What we’re going to do is include an if conditional in this file to determine if a product falls under a specific category, and if it does, then single-product.php should load up the custom template you created. You do not need to rename the single-product.php filename, you’re just going to open it up in your favorite code editor and modify some of the PHP in it. So open up single-product.php in your code editor, and find this code:

woocommerce_get_template_part( 'content', 'single-product' );

You’ll want to replace it with this code:

global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;

if ( in_array( 'YOURCATEGORY', $categories ) ) {
  woocommerce_get_template_part( 'content', 'single-product-YOURCATEGORY' );
} else {
    woocommerce_get_template_part( 'content', 'single-product' );
}

Where you see YOURCATEGORY, you will want to replace it with whatever your category slug is, and whatever you renamed your content-single-product.php file to. So for example, if my category slug was ‘hats’, and my content-single-product.php file was renamed to content-single-product-hats.php. Then my code would look like this:

global $post;
 $terms = wp_get_post_terms( $post->ID, 'product_cat' );
 foreach ( $terms as $term ) $categories[] = $term->slug;
if ( in_array( 'hats', $categories ) ) {
 woocommerce_get_template_part( 'content', 'single-product-hats' );
 } else {
 woocommerce_get_template_part( 'content', 'single-product' );
 }

4. Upload and Test

Cool, you’ve edited your files, renamed them, etc. Now it’s time to upload these files to your site. Make sure you have a subfolder called /woocommerce/ in your theme’s directory. Both files go in the same directory. You want to make these kinds of edits in that folder in your theme so you don’t end up overwriting the original WooCommerce files.

Now all you have to do is check out your product or product category to make sure your custom template is showing up properly and you’re done!

Resources

The following threads on Stack Overflow were invaluable resources for me.

WooCommerce Custom Single Product Template, StackOverflow

WordPress WooCommerce Template File Override, StackOverflow



Pen Review, Platinum Preppy, Fountain Pen

The Platinum Preppy is a common recommendation for people interested in getting into fountain pens or trying out a fountain pen for the first time. At $3.00 per pen, it’s a great way for someone to hold, try and test a starting level fountain pen before investing in something a little more expensive. With that having been said, the Preppy is a good starter pen, but it is just that.

The Platinum Preppy Pen Stats

Model: Preppy
Make: Platinum
Type: Demonstrator Fountain Pen
Tip Size: 0.3mm, Fine
Nib Type: Steel Nib, Standard
Body Material: Plastic Body
Tested On: Kokuyo Lined, Rhodia Dotted & Staples Lined Paper

The Pictures

Platinum Preppy, 0.3 Fine on Staples Lined.

Platinum Preppy, 0.3 Fine on Staples Lined.

Platinum Preppy, 0.3 Fine on Rhodia Dotted.

Platinum Preppy, 0.3 Fine on Rhodia Dotted.

Platinum Preppy, 0.3 Fine on Kokuyo Lined.

Platinum Preppy, 0.3 Fine on Kokuyo Lined.

Platinum Preppy, Top View

Platinum Preppy, Top View

Platinum Preppy, Deconstructed Side View

Platinum Preppy, Deconstructed Side View

Platinum Preppy, Nib View

Platinum Preppy, Nib View

Platinum Preppy, Side View

Platinum Preppy, Side View

Platinum Preppy, Side View

Platinum Preppy, Side View

 

Review of the Platinum Preppy Pen

I had a fountain pen when I was much younger. It was a sac-fill system which means that you have a sac that you use to draw ink into in order to use. This was in the late-80s to early-90s in Vietnam. I remember having to clean it, dispel the ink after a week and soak it before re-inking it. This was a long time ago when I was in grade school so I don’t remember much about that pen, what make or model or even the kind of ink. And I only know what color the ink was because saw some of my old notes from when I went to school back then. For a long time, I figured fountain pens were too expensive to get into and I had resigned myself to pens that you could buy in a pack of 20 at the grocery store. So when I discovered the world of affordable, starter fountain pens, I was thrilled.

I noticed the Platinum Preppy was a common recommendation for beginners or people just looking to get started in fountain pens (it really can be a slippery slope) so I decided to give it a try. At $3.00 per pen, the Preppy is marketed as a starter and while you can buy refills for it and even use a converter (more on that later), it really works well as a disposable pen to test the waters before you dive in.

From my writing tests, the Preppy does very well for a fountain pen at this price range. I have two pictured above, but only tested the 0.3 or Fine nib. It will lay down a decent amount of ink, especially given that it’s a fine nib and has a fair amount of glide and smoothness. People who have gotten into other fountain pens will be able to tell you about this “buttery” writing feel where the nib glides so smoothly along the paper. The Preppy lacks that in my opinion. But at the same time, you can’t really expect it to have the feel and it does a good enough job that this will still feel better than scratching your way around with a fine tipped rollerball.

It skipped a couple of times on the Kokuyo paper, skipped several times on the Rhodia dotted, but was fairly consistent on the Staples paper, however I noticed a lot of unintentional line variations on the Staples paper. Probably due to the quality of the paper more than the pen itself.

When you purchase the Preppy, you’re getting the pen and an ink cartridge included. Platinum has a wide variety of colors and nib sizes. You can get the pen and cartridge in black, blue, green, purple, pink, red and blue black (as far as I know) and nib sizes come in extra fine, fine and medium. You can also get refill ink cartridges with whichever color you’d like, these are typically inexpensive and come in packs of 2, 6 or 12: Platinum Preppy Ink Refill Cartridges

If you decide that you really love your Platinum Preppy and want to keep using it but don’t want to use cartridges or feel like you need to have more color options, the Preppy is compatible with Platinum’s twist-style converter: Platinum Fountain Pen Converter

All that having been said, as far as writing feel for a fountain pen goes, pushing aside the price point and the fact that this is a starter pen, the Preppy is only OK. It’s not anywhere near as smooth a writer as other fountain pens, it has a nice form factor but there’s a lot of branding covering the demonstrator body (that’s when a fountain pen has a clear body so you can see through to the cartridge, converter and sometimes the other elements of the pen too) and a giant warning label on the side, so it defeats the purpose of a clear-bodied pen a little bit. It also skips more than other fountain pens I’ve used and tried, and it really struggles and skips a ton when I’m trying to lay down a line really fast like a signature for example.

Available On:
Amazon, Platinum Preppy, Fine Nib (0.3mm) 7 Colors Set
Jetpens, Platinum Preppy



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



Pen Review: Morning Glory, Mach 3 Pen

The Morning Glory, Mach 3 was one of the first pens that presented itself when I went digging in my stash. The one I have is an emerald green that lays down the same color ink. It has a nice form factor, with a decent balance and is somewhat reminiscent of a semi-skeleton or semi-demonstrator fountain pen. It is, however, a liquid ink rollerball. That means it has a body filled with ink and dispenses it through a ball mechanism on the tip.

The Mach 3 Pen Stats

Model: Mach 3
Make: Morning Glory
Type: Liquid Ink Rollerball
Tip Size: 0.38mm
Body Material: Plastic
Tested On: Kokuyo Lined, Rhodia Dotted & Staples Lined Paper

The Pictures

You’ll have to excuse my terrible photography skills. I haven’t done anything photography related in almost a decade. I’ve tried to get the nicest, clearest and decently lit photos I could!

Morning Glory, Mach 3, Tip

Morning Glory, Mach 3, Tip

Morning Glory, Mach 3, Staples Lined

Morning Glory, Mach 3, Staples Lined

Morning Glory, Mach 3, Rhodia Dotted

Morning Glory, Mach 3, Rhodia Dotted

Morning Glory, Mach 3, Kokuyo Lined

Morning Glory, Mach 3, Kokuyo Lined

Morning Glory, Mach 3, Cap Off

Morning Glory, Mach 3, Cap Off

Morning Glory, Mach 3, Body

Morning Glory, Mach 3, Body

Review of the Mach 3 Pen

The Morning Glory, Mach 3 pen has a nice glide for the most part. It dispenses a consistent line the majority of the time and the emerald green is vibrant and pleasant. One of the reasons why I test on lower quality lined paper as well as the higher quality papers is because some of these pens might end up surprising me in a write test. The Mach 3 is one such pen.

It laid the most even line on the Staples Lined Paper, and struggled a little bit on the Rhodia. It was mostly consistent on the Kokuyo, but I have to admit that its best and most consistent test came out on the lowest quality paper I tested it on, which just so happens to be the Staples. Happily, the chances of most people writing their notes on Rhodia or Kokuyo are less than people writing their notes on a sheet of Hillroy or Staples brand. The pictures above will show how it did on the Rhodia, you can see it struggled on ‘achieved’, ‘know’ and the loops, the Kokuyo went mostly well until it got to ‘that’, the loops and ‘fastly’.

The pen is a little tiring to hold if your grip has it resting on your middle digit. This only happens to me at around the half hour mark though. It’s a full plastic body, and the grip is of the same material. The sizing and weight are fine, tending to be a little lighter than most of the pens I have. Something about the grip doesn’t allow it to be comfortable in my hand. Though, I’m always of the opinion that what feels good to me might not be true for someone else, so always take my grip impressions with a grain of salt until you try it yourself.

I’m overall pleased with the Mach 3. It’s a nice feeling writer that’s mostly consistent and the line quality is pretty good. Generally what I noticed with these liquid ink pens is that if you don’t have a very quick writing speed, the lines will tend to be more consistent and you won’t experience any skipping as you go. Another thing that I might be experiencing here is the slant at which I tend to hold my pens, if you angle the pen so that it’s a bit more perpendicular to the paper, you might get a better consistency in line quality.

I love the color of the emerald green I have and this line comes in black, blue, green, lime green, red, orange, pink light blue, purple and more. The color selection alone is a winner in my book. Mach 3s sell for $2.00 each so you can freely experiment with colors or even get one to try out and see if it will fit your writing style. At the moment, I’m unaware of the Morning Glory, Mach 3 pen having any other tip size than 0.38mm, which most people would consider to be a fine line.

Available On:
Amazon, Morning Glory Mach 3 Roller Ball Pen – 0.38 mm-Fine Point Tip (Pack of 12)
Jet Pens, Selection of Morning Glory Mach 3 Rollerball Pens



Stationary and Writing Instrument Reviews, Ahoy

As one of the sad side effects of website design, development and coding in general, my handwriting has suffered. I’ve been coding since middle school, and like many others, I type much faster than I can write. Therefore, I prefer typing whenever possible or when I need to note something down very quickly. Which in this line of work–is a lot. I’ve taken up writing my notes instead of typing them in an effort to do two things:

  1. Help me remember things better. I find the physical act of putting words and code onto a page helps them stick better than typing it up.
  2. Improve my handwriting and help me get better at hand lettering.

As much as I enjoy the code, I’m a designer at heart and hand lettering has been one of those late blooming passions that I discovered can be really relaxing and very satisfying. I’m not great at it, but it’s a hobby and hobbies are meant to be fun. I also enjoy trying out different pens, inks, brushes, brush pens that I’ve amassed and used quite a few by now. So I wanted to add another function and feature to this blog: stationary and writing instrument reviews.

I’ve used a lot of pens and have a lot lying around. It used to be a pretty simple exercise. Need to write something down? Reach for the closest Bic. And while Bics are easy to find, and they work well enough. I’ve found a little more satisfaction in other pens since then. I was also that kid in school who lamented having fun pens to write notes and was always on the look out for the “holy grail” pen that provided the best flow of ink, the best writing feel wrapped in a comfortable grip. So I’ve tried a lot of different pens as I discovered how much I really, really like to write things down.

This isn’t a new thing I’m launching into doing either. It’s a little known tidbit about me, but I’ve kept three to four blogs before. Most of them gone by now, but the one that still remains is That Smell, a fragrance and perfume reviewing blog. It taught me a lot about the fragrance industry, the science behind it, the trends, the big and small players and I met a lot of amazing people. That Smell is still going, though decidedly less strong than it used to since coding, freelancing and designing have (happily) taken up my life.

But putting perfume reviews here would be a little awkward since software, design and websites don’t have much to do with perfumes (unless a perfume house needs a new website *nudge nudge*). But stationary, writing, hand lettering and the tools used to write do have to do with my line of work. So starting in 2016, we’re going to see pen, stationary and office tool reviews and articles as a way to spread things out between software, coding and design related posts.

Long story short, it’s my blog and I want to have some fun. See you in 2016!