Embarrassingly Elaborate Solution to a Codewars Algorithm

I’ve been thinking about writing a post like this for a while but have put it off because, frankly, it’s pretty embarrassing…

Today, I saw a post in the Free Code Camp Forums that made it clear, however, that I’m not the only one that goes through this.  So hopefully this post will encourage other beginners to keep going, even if their code looks terrible in their own eyes…

The purpose of this post won’t be to walk through the algorithms and explain everything that’s going on, but rather to emphasize how different two answers to the same problem can be.

Codewars

Codewars, as I’ve mentioned in previous posts, is a great way to practice solving algorithm challenges.  It can be pretty humbling at times, though, because after you solve the problem, you have the opportunity to look at other people’s solutions.

So, when you solve what you thought was a difficult challenge, only to see that others have solved it in one or two lines of code, it makes you wonder if you’re writing in the same language.  When you realize you are, you wonder further if this coding thing is really for you…

The upside to this, and, in my opinion, the real strength of Codewars, is that you can learn from these solutions…  I’ve only done a handful of algorithms on this site so far, but I’m going to show my first and last solutions as examples of how things can improve.

My First Codewars Solution

The first algorithm I solved at Codewars was called ‘Decode the Morse code’.  Try not to laugh….

The site’s description of the algorithm is as follows:

So, in thinking about the solution to this algorithm, I immediately pictured various ‘for’ loops to split the Morse code into words, then letters.  Then I could replace the Morse letters for real letters and reassemble the message using more ‘for’ loops.

Here is what I came up with…

I was feeling pretty good about myself (it worked after all!) until I saw some of the top rated solutions…

Here are a couple:

Pretty big difference, huh?  These 3 solutions, put together end to end, took fewer lines than my 1 solution did…

I want to make a couple points about this…

My Latest Codewars Solution

First, if you use these solutions to learn from, you can get more clever with your own solutions, and in the end, make yourself a better programmer.

Here’s an example of an algorithm I submitted a couple days ago.

Algorithm details:

My solution:

Most of the top solutions were variations of this:

Ok, so was this last attempt better??  Sure…  Still room for improvement? You betcha…

Looking through past examples definitely helped me put together a more concise solution for this problem, but I still have a lot to learn…

For instance, looking at the answers to this algorithm reminded me that the array.filter() method doesn’t change the array on which it is called. So, once I filtered the non-zero values into a new array, I still had the original array to work with.  I could have used it again to add the zeros to the end of the new array.

Hopefully, next time I come across a problem like this I’ll remember the more elegant solution.

In my experience, learning a new skill, especially one as difficult as programming, is all about repetition and practice.  So I encourage you (and myself too) to use sites like Codewars to practice these skills over and over.

I also encourage you to take the time to look through other people’s solutions and learn from them.  It’ll probably help with your approach to your next one.

It ain’t necessarily about having the shortest solution…

The second point I want to make is that the shortest solution isn’t necessarily the best solution.

We can argue that ‘for’ loops are actually faster than native functions like array.filter() and array.map(), and they are, but that argument is mostly semantic.  Unless you are writing an application that demands extremely high performance, it is unlikely that the user will see a difference between the two.

I believe, therefore, that prioritization should be placed on the readability of the code you write.

Going through the process of teaching myself how to code, I’ve read many examples of code written by others, and can say for certain that all code is not created equal.

Some code is nicely written and readable…  Other code is like a plate of spaghetti and impossible to decipher.

Let’s go back to the answers to the first algorithm.  My code, while drawn out and overly complicated, is fairly easy to follow.  The last two solutions listed, while being the shortest, are not that easy to read (at least to a newbie like me).

I’d argue that there’s gotta be a happy medium, maybe something like the one written by czyzykowski.  Their solution is logical, modular and very easy to follow.

Feel free to comment below if you disagree, like I said, I’m still new to this, so maybe those last 2 examples are perfectly readable to someone who’s been at this a while.

Bottom Line

I think the takeaway from all this should be – don’t worry if your code looks like a fanewgi wrote it, just keep plugging away…

Read code others have written and keep writing more of your own.  Before you know it, you’ll look back at code you wrote a while ago and realize just how far you’ve come!!

That’s it for now, I hope this helped straighten out the code…

-Jeremy

Getting Feet Wet with Internet of Things (IoT)

As I mentioned in my last post, I’m interested in the ‘Internet of Things’ as a way to use and strengthen the skills I’m learning in the back end program at Free Code Camp.

So last week I ordered the SparkFun Johnny-Five Inventor’s Kit.  Over the weekend, I started playing around with it, and as a bonus, my two boys (ages 9 and 12) helped out!

Keep in mind, the title of this post is ‘Getting Feet Wet…’, so nothing I’ve done so far is earth shattering, but you have to start somewhere, right?

The Kit

The kit included the Tessel 2 board and a ton of peripherals  (LEDs, a breadboard, 2 motors, resistors, an LCD screen, a magnetic door switch, etc, etc).  Here’s a picture of the Tessel 2 board plugged into a micro USB cable.

Tessel 2 Board
Tessel 2 Board

The reason I chose this kit (there are quite a few on the market) is that it came preloaded with Node.js.  I figured this would be the easiest way to get started using full stack JavaScript (Node.js along with Johnny-Five).

Granted, you can download Node to the other boards on the market, but considering I was an IoT virgin, I went with the preloaded option.

It also comes with a great Experiment Guide that takes you through 14 experiments to get started.  The guide also contains links to relevant tutorials so you can learn on a deeper level as you go.

I started by reading a few tutorials like ‘What is a circuit?‘,  ‘Voltage, current, resistance and Ohm’s Law‘ and ‘How to use a breadboard‘ to freshen up my knowledge of circuits and electronics.  The experiment guide turned out to be an awesome resource in helping to get started.

Getting Started with the Tessel 2 Board

The first few pages of the experiment guide explain what a development board is, what it can be used for and describes the particular features of this board.  The Tessel 2, among other things, has 2 USB ports, an Ethernet port and WiFi!

It then takes you through software and hardware installation and setup.

The only software you’ll need is a text editor (I’ve been using Atom to develop my FCC projects, so continued to use it for this), Node.js and a terminal application.  The guide walks you through the installation of each of these if you don’t already have them on your computer.

The hardware setup consisted of connecting the board to your computer via both USB and Wifi.  You also have the chance to name your board if you want, so I named mine Lucy (after my late, great boxer)…

Lucy
Lucy

At that point, you’re ready to get started with experiments!

Not counting the time I took reading the tutorials, it took less than a half hour from the time I opened the box until I was ready to run some experiments.

Time for Experiments!

The first experiment in the guide (and the first one I did with my kids) was getting an LED to blink.  Exciting right?  Yeah, my kids weren’t terribly impressed either…

We started by building the very simple circuit outlined in the experiment guide.

Experiment 1 Circuit
Experiment 1 Circuit from the Sparkfun Experiment Guide

As you can see from the diagram above, using the breadboard to make the connections, we made a circuit from one of the ports in Lucy (our board) to the anode (+) of the LCD, then from the cathode (-) of the LCD, through a resistor, back into the ground port of Lucy.

With the circuit complete, now we had to write the code that will make the circuit do what we want.

The Code…

This is the code the guide provides as a starting point.  If you’re new to Node.js, the experiment guide does a great job of walking you through and explaining the lines of code.

Obviously, this isn’t a complete Node tutorial, as it would take too long and I don’t have the experience (yet) to cover such a big topic, but we can walk through this code to see what it does…

One of the great things about Node is the vast number of modules that are available for use.  A module is basically a block of code that does something for us.  There are modules for node that handle all kinds of things.

As you can see by the top two lines of code above, we included the ‘tessel-io’ and ‘johnny-five’ modules using require() and set the modules equal to variables (Tessel and five respectively).

We can now reference those variables to have full access to the modules functionality.  If you’re new to Node, that may be confusing, but keep reading for examples.

There’s actually quite a bit going on in the next block of code.

By writing ‘new five.Board()‘, we create an instance of a Johnny-Five Board by referencing the Johnny-Five object, Board, using the variable ‘five’ that we created in line 2.

Again, similar to what we did in the first 2 lines, we set the new Board equal to a variable, ‘board’, so we can access and manipulate it later.

io: new Tessel() is telling our program to use the Tessel() object to communicate with our board.  Tessel, if you remember, is the variable we created in line 1 and set equal to require(‘tessel-io’).  So, basically, we are telling our program to use the ‘tessel-io’ module to communicate with our board.

Now that we have the modules we need, and have created an instance of our board, we can actually do something with it!

The last block of code creates a listening event for our board.

board.on(‘ready’, callback) tells our program that when the board is ready (done initializing), run the callback function.  In this case, our callback function, which is written in the new ES6 Syntax, () => {} , is contained on the 2nd 2  lines.

Again, we use ‘five’ to access the Johnny-Five module and create a new LED.  We set our new LED equal to a variable, ‘led’.  The ‘a5’ parameter tells our program that our new LED is connected to the A5 pin in our board.

We can then use ‘led’ to access our LED.  led.Blink(500) tells the LED to blink every 500 milliseconds.  Which, it did! (after we loaded and ran the program)

And the crowd goes wild!!

Well…  Maybe not wild, it’s only a blinking LED after all.  But that’s not the point!

We used our new coding skills to do something!  Actually, that might be overstating it too, we copied the code from the experiment guide.  But the point is, we completely understood the code and can now use this to build on.

We ended up running experiment 3 too.  This time we were able to control the LED with a button.  You can check out the circuit and the code in the guide, but here are some pictures of our version.

LED with button circuit
The circuit used to control an LED light with a button using a Tessel 2 board.

The boys were a little more impressed with this experiment, as they could actually control something.

Tessel 2 lighting LED with Button Switch
Tessel 2 lighting LED with Button Switch

All in all, it was a great couple hours spent with my boys, hopefully getting them excited to learn something.  I definitely plan on digging deeper into what this kit can do and hope to use my newfound Node skills to design some more custom projects.

I’ll be sure to write up future adventures in IoT here at Crooked Code.

Please leave comments below if you have any suggestions for interacting with IoT or personal experiences you think might help others.

That’s it for now…  Thanks for reading.

-Jeremy

In the spirit of full disclosure, the two links to the Sparkfun Kit contained in this post are Amazon (which is where I purchased it) Affiliate links, which means I would get a small (very small) percentage of your purchase if you click on the link and buy one…  In the unlikely event that I see any proceeds from this, they will be used to offset part of the expense of running the Crooked Code site.  Thank you.

End of Summer Wrap-Up

It’s been a couple weeks since I’ve had the chance to write a post, as things have been a little crazy around the Crooked Code household…

Football season started for my two boys, they started school this week and my wife went back to work this week!! Hopefully, now things will start to settle down a bit.

Anyway, enough about that, let’s talk about what we’ve accomplished this summer and what we want to accomplish this fall….

What I’ve done this summer…

As I mentioned in a previous post,  I finished the front end certificate at Free Code Camp in July!!

I decided to work on the Back End Program at FCC, then jump back and complete Data Visualization.  Thus far, the back end has been difficult, but enjoyable.

It’s been difficult in that I’ve really had to change gears in my head. Node.js and working on the server side have been completely different than any other coding I’ve done in the past (granted, it’s a fairly limited past as far as coding is concerned).

Diving In…

I started the back end program by working through the Cloud9 modules for Git, Node.js, Express.js and MongoDB.

If I’m being honest, I found these modules to be pretty useless…  I didn’t learn much from them, and half the time I wasn’t even sure what they were asking me to do.

As a beginner, I think it would have been more useful to have a better intro to the languages and better explanations as to what I was trying to do with them.

Instead, I felt like I was trying to satisfy the requirements of some very random modules so I could move on (and getting nothing out of it in return)…

I realize, that’s just my personal opinion and that different people learn by different methods…

Intro to the very helpful Ninja!

Speaking of actually learning, I found a very helpful tutorial series on YouTube called Node JS Tuturial for Beginners by the Net Ninja.  I may have mentioned this guy before and I highly recommend these videos if your starting out learning the back end.

There are quite a few videos in the series, but each one is short and to the point and very easy to understand.  I watched each of the videos and worked along side them in building a ‘To Do’ app in the last 7 or 8 videos.

In addition to a great intro into Node.js, one of the cool tangential things I learned from this series was working with Atom.

The ‘Ninja’ takes you through the steps of setting up Atom, installing Node, npm, etc.  I’ve been working in Atom ever since and find it a much better environment to develop the back end projects than working on Cloud9.

Initial Thoughts on Server Side

At the risk of sounding a little naive and corny, learning how servers work has opened my eyes to the potential you have as a full stack developer.

Let me try to explain what I mean…

I feel like I learned a ton in the Front End program but I always had a nagging in the back of my head like, ‘yeah, these new skills are great, but how do I actually use this to build something bigger than a one page app??’.

Working with Node and Mongo and everything else involved in the back end program (yes, even Git) has calmed that nagging a bit and given me a sense of the bigger picture.

Granted, I’m less than a month into this and have a lot of work ahead of me, but it’s very motivating to start tying things together like this…

Progress Thus Far..

At this point, in addition to the Cloud9 ‘learning’ modules, I’ve completed 3 of the 5 API projects.  Feel free to check out my Timestamp MicroserviceRequest Header Parser Microservice and URL Shortener Microservice.

You can find the code for all these apps on my GitHub page. Please feel free to comment below with any suggestions or questions about my code.

Where we’re heading this fall…

First and foremost, I’ll be working towards completion of the Back End Certificate.  I plan on finishing up the last two API projects then moving right on to the full stack ‘Dynamic Web Application Projects’.

Additional Resources

In addition to the Free Code Camp projects, I’ve continued listening to tech related podcasts.  I mentioned most of the ones I’m listening to in a previous post, but have picked up a few new ones as well.

Two of my favorite new ones are FiveThirtyEight Elections Podcast and IoT Podcast.

The Elections Podcast is by the awesome people at FiveThirtyEight.com where they talk about how they are applying their models in an attempt to predict the outcome of this year’s US presidential elections.  It’s very relevant and very cool…

Internet of things

As I’ve been working through the back end program at FCC, I’ve been trying to think of ways to start applying what I’m learning in the real world.

One idea that I’ve been giving a lot of thought to lately is the internet of things (hence the IoT Podcast).

The internet of things, if you don’t already know, is a broad term that describes all the real word items (refrigerators, cars, wearables, thermostats, etc, etc, etc) that are hooked up to the internet and can be sensed and/or controlled remotely, the so called ‘smart’ items.

Just yesterday I ordered a beginners kit that includes a board and a bunch of sensors and motors so I can start playing around with this stuff.  I’m really excited about it and one of my sons wants to get involved too, which makes it even better!

Johnny-Five!

Considering the FCC program is full stack JavaScript, I’m planning on using the JavaScript framework called Johnny-Five which enables you to run full stack JavaScript, including Node, to control the robotics.  I’ll be sure to include my experiences here at Crooked Code.

A friend of mine, Serg Chernata, just started a blog called ‘Bits & Pieces‘, where he’s going to discuss a bunch of tech related topics, including his experiences with IoT.  In fact, his first post was about setting up a Raspberry Pi as a home server to host his blog.

I’ve included a link to his blog on the sidebar of this site under ‘Recommended Blogs’.  I’ll keep adding to this list as I come across sites that I find interesting and useful.

Once again I’ve written a much longer post than originally planned, which is not easy for someone who says so little in the real world!  Hopefully, if you’re still reading, you got something out of this.

Until next time…

-Jeremy

 

 

FCC Advanced Algorithm Scripting Challenge – ‘Symmetric Difference’

Let’s tackle another Free Code Camp advanced algorithm – ‘Symmetric Difference’.  The challenge here is to ‘create a function that takes two or more arrays and returns an array of the symmetric difference ( or ) of the provided arrays.’

The symmetric difference of two sets of elements is the set that occurs in either one of the two sets, but not both (i.e. the symmetric difference of [1,2,3,4] and [3,4,5,6] is [1,2,5,6]).  For more reading on symmetric difference, check out this wiki page.

Free Code camp gives us the following as a starting point:

This is another case where we have to write a function for which we need to handle an unknown number of arguments.  To accomplish this, we’ll be using the arguments object.  I’ve covered the arguments object in a previous post, ‘Seek and Destroy’.  If you are unfamiliar with or would like a refresher of the arguments object, please check it out.

One of the helpful hints FCC provides us with is a link to the Array.prototype.reduce() method.  The arr.reduce method is a great way to cycle through and apply a function to each element of an array.

The arr.reduce method takes 2 arguments, a callback function (which will be applied to each element of the array) and an initial value (the element to provide as the first argument to the first callback function call – see here for more).

If you’re new to JavaScript, or somewhat unclear of what a callback function is, JavaScriptIsSexy.com has an excellent post on callbacks.

The callback takes a possibility of 4 arguments – previousValue, currentValue, currentIndex and array.  This is important, as it means when we write our callback function, we will have access to these 4 values within the function (for further clarity on exactly what the four values are, check out the MDN link mentioned previously).

I think we should break down this challenge into two main problems.  We need to:

  • Write a function that returns an array of the symmetric difference (⊕) between two given arrays
  • Use this function to handle an unknown number of arguments. For example:
    • find (arg1 ⊕ arg2)
    • if there’s an agr3, find arg3 ⊕ (arg1 ⊕ arg2)
    • continue for argX

At this point, I’m going to start discussing my solution to the problem.  If you’re working through FCC, I’d suggest attempting a solution on your own given what we’ve discussed above. Otherwise, proceed on…

Spoilers_ahead

Let’s start by writing the function we’ll use to calculate the symmetric difference between two arrays.

In other words, we need to write a function that receives two arrays as arguments, then returns an array of the numbers that are in one of the argument arrays, but not both.

One way to do this is to

  • create a new empty array (curDiff) to store the symmetric diff
  • use arr.reduce() to cycle through each array (need to compare each array against the other, not just one against the other)
  • in the callback function of arr.reduce
    • check if an element is in the other array or in the curDiff array (to prevent duplicates in curDiff)
    • if not – push element to curDiff
      • hint – arr.indexOf() will return -1 if the given element is not found
  • return curDiff

Here’s the JavaScript code:

We now have a function (findSymDiff()) that we can use within our main function to get the symmetric difference between two arrays.  We now have to set up the logic to handle an unknown number of parameters received by our main function.

Our logic (using the arguments object) can look something like this:

  • create new array (symDiff) to store the array returned by findSymDiff()
  • compare arguments[0] to arguments[1] using findSymDiff()
  • cycle through argument[]
    • compare symDiff to arguments[x]

To accomplish this, we can set up a simple for loop.

If we set

we can call

in our for loop starting at i=1 and loop while i<arguments.length.

Then all we have to do is return symDiff!

Here’s how everything looks when we put it together:

This solution passes all of the FCC test cases.

Thanks for reading, feel free to leave comments or additional solutions below.  And if you’re working through Free Code Camp, hopefully this helped straighten out the code.

-Jeremy

 

Front End Certificate at Free Code Camp – Complete!!

Five months and one day after I discovered Free Code Camp, I’ve completed my Front End Certificate.

frontEndCert

It took a little longer than I had originally planned, but considering that in addition to learning HTML, CSS and JavaScript from scratch, I maintained a full time job and tried to spend (at least some) time with my family (including coaching a season of baseball), I’m pretty happy with the accomplishment.

A couple thoughts on the process….

When I discovered Free Code Camp, I rolled up my sleeves and began the front end development section with tunnel vision, focused only on completing the certificate.   Along the way, my focus broadened… I began to realize that this process isn’t just about completing a certificate, but becoming a strong developer.

To that end, I searched for additional resources to supplement the Free Code Camp curriculum.  I covered a lot of these resources in a previous post, but mostly it involved listening to podcasts, reading books, watching YouTube videos and practicing algorithms.

I also started this blog.  If you would have told me before I started this process that I would start a blog on learning to code, I would have labeled you crazy…

I’m an introverted guy and generally keep my thoughts to myself, so expressing myself in these posts isn’t exactly second nature. I think, however, that doing so has significantly enhanced what I’m getting from this process (and hopefully helped at least a couple others in return).

I’ve also found that trying to explain the solution to an algorithm is, in many ways, much harder than writing the solution itself!  I think this has certainly helped strengthen my coding skills and plan to continue working through the solutions to many of the freeCodeCamp algorithms and projects here at crookedCode.

So, if you find yourself getting frustrated with your progress in your own learning to code journey, take a step back and ask yourself what else you could be doing to broaden your learning experience.

And finally, I want to say – Learning to code is hard!  

This journey has been difficult in many ways I could not have predicted at the onset. First, of course, learning a new skill (any new skill) can be difficult.  Coding is certainly no exception, in fact, I’d argue just the opposite.  

I feel the difficulty is often overlooked in the many articles (at least the ones I’ve read) that proclaim everyone can learn to code.  Many of these articles fail to mention that it’s going to take a lot of work and a lot of extremely frustrating, trying moments, especially if you’re teaching yourself.  

I’m not arguing against the idea that people should learn to code…  If learning to code interests you, then by all means, let nothing stand in your way. Before you start, however, make sure that it’s something you really want to do and make sure you’re prepared to commit the time and mental energy to accomplish your goal.

In addition to the difficulty inherent to learning to code, many other aspects of the journey add to the difficulty…

Time management has been a big one for me.  Keeping a full time job, having a wife and two active sons and learning to code is a very full plate.  Through most of baseball season, I just coded whenever I could fit it in the schedule…

It seemed like there was something going on every night and throughout the weekend, so whenever there was a break, I would try to put some work in.  I’ve got to say though, that pace is unsustainable if you value your mental health and the happiness of your family.

Since baseball has finished, I have blocked off two evenings and one day on the weekend that I devote to learning to code.  Everything else (at least when I’m not at my full time job) can be spent with family or catching up with stuff around the house.

If you are learning to code and have other personal commitments, I highly recommend blocking off a schedule of when you plan to work. Otherwise, you always feel like you should be working and everything else in your life takes a back seat, and suffers because of it….

Of course, there are other things like maintaining self-confidence, battling impostor syndrome, deciding what to learn, setting up a development environment, etc., etc. but this post is already longer than I had planned.  Just know that if you are struggling in your journey to learn to code, you are not alone, there are plenty of us out there in the same boat.

So, if you’re still reading this, thank you and good luck on your own journey.  I’ll keep posting here at crookedCode to try to make things easier for those that actually read it.   As for right now, I’m off to start the back end development certificate at Free Code Camp…

-Jeremy

FCC Intermediate Algorithm Scripting Challenge – ‘DNA Pairing’

 

Today, we’ll cover freeCodeCamp’s Intermediate Scripting Challenge ‘DNA Pairing‘.  The challenge here is to write a function that accepts a string of characters and returns a 2D array of matched base pairs.

If you’re not caught up with your molecular biology, here’s a quick lesson…

Molecular Bio 101 (mostly not needed to solve algorithm)

By Zephyris at the English language Wikipedia, CC BY-SA 3.0
By Zephyris at the English language Wikipedia, CC BY-SA 3.0

DNA is the double stranded nucleic acid that carries your genetic information.  Each single strand is composed of units called nucleotides, of which, there are four – cytosine (C), guanine (G), adenine (A) and thymine (T).  In double stranded DNA, these nucleotides bond in specific base pairs, A with T and C with G.

DNA stores all kinds of biological information and make up our chromosomes, which, in turn, make you who you are…  Enough bio, let’s get back to solving the algorithm….

Bio Class Dismissed…

As we get into the intermediate and advanced algorithm challenges, each challenge will have multiple (even many) approaches to a solution.  My plan with Crooked Code is to explain the solution that I used, then search for solutions used by others in order to illustrate the various ways an algorithm can be written.

This is what freeCodeCamp gives us as a starting point for ‘DNA Pairing’:

The instructions provided for this challenge tell us that we’ll be getting a string as an argument and we must return a 2D array that matches up each element (letter) with it’s base pair counterpart.

Let’s get started working on a solution…

I started by ‘splitting’ the string argument into an array using string.split() method.  I covered string.split() in depth here.   I also created some variables that we’ll use later in the function.  My ‘pairElement’ function now looks like:

We now must scroll through ‘singleArr’ and pair up each element with it’s matching pair.  We can use a for loop to scroll through the array, but how can we match up the pairs?

A bunch of if/else statements would work but a switch statement is a better option here.  A switch statement will evaluate a given expression, then transfer control to the case that matches the outcome of the expression.

I’ve included the syntax of a switch statement written by mozilla in order to make the explanation easier.

In our case, the expression will be just a letter, as will each case value.  We can then write a statement to be executed for each individual case.

To sum up the logic for our algorithm…

  • split the given string into an array
  • loop through array and match each element with it’s pair
  • ‘push’ each new pair into 2D array
  • return 2D array

At this point, we’ve covered everything needed to solve the ‘pairElement’ function.  If you’re working through the freeCodeCamp curriculum you may want to go try to solve it on your own, otherwise, read on…

Spoilers_ahead

Here’s the solution to the ‘DNA Pairing’ challenge that I came up with:

The freeCodeCamp wiki page (written by @Rafase282 and @sabahang) provides 2 solutions to this algorithm challenge.  The first, ‘basic’, solution is very similar to mine, using a switch statement, so I won’t include it for the sake of redundancy.

The second, ‘intermediate’, solution uses an object, and we haven’t really covered objects in much detail here at Crooked Code.  I’ll include the code below so we can see a second, very different solution, but won’t provide an explanation, as objects are far too big of a topic to cover at the end of this post.

You can see an explanation to this solution at the wiki page.

That’s it for now, hopefully this helped straighten out the code…

-Jeremy

FCC Intermediate Algorithm Scripting Challenge – ‘Boo who’

This post will cover freeCodeCamp’s intermediate algorithm scripting challenge ‘Boo who’.

‘Boo who’ challenges us to write a function that checks if a given argument is classified as a boolean primitive.  If so, return true, if it’s anything else, return false.

The solution, once written, is quite simple but there are a few key concepts we have to understand before we can get there.

Here’s what FCC gives us as a starting point:

Now, we have to figure out…  What the hell is a boolean primitive?

First, let’s consider what boolean means?  Boolean is a word used in both math and computer science.  In computer science, it generally refers to a data type or a variable that can have only one of two values, usually true or false.

Boolean variables are useful in controlling the logic of an algorithm and are generally used in conditional statements such:

Second, what does primitive mean?  Mozilla, as always, gives a pretty good description of a primitive.  Basically, Mozilla tells us a primitive value ‘is data that is not an object and has no methods.’

Tangent on Primitive Types vs. Reference Type

According to the latest ECMAScript standard, JavaScript has 7 data types. 6 primitive types which are string, number, boolean, null, undefined and symbol and one reference type – object.

The difference between the two types becomes confusing when you consider that JavaScript provides constructor functions that allow you to wrap boolean, number and string values as objects, which changes them from primitive to reference type.

Consider the following:

Problems start to arise if you try to use a string object like a string primitive.  Keep in mind that a string object is still an object, and behaves like one.

For instance:

Given that JavaScript will allow you to use the methods associated with an object prototype on the primitive values (example below), it is best to use primitive types whenever possible.

FYI, Effective JavaScript by David Herman has a good section on why primitive types should be preferred to using object wrappers and I derived some of my examples above from those found in his book.

Ok, enough about Primitive Types, hopefully this has been more than enough info to solve ‘Boo who’.

End of Tangent

Check out the Mozilla link above for further explanation of primitive values (or this one for info on the Boolean object), but for our purposes in solving ‘Boo who’ we now know that the only boolean primitives are true and false.

So, now we have to fill in the booWho function above, checking if bool equals true or false.  In doing so, we’ll use the strict equality operator (===) vs. the loose equality operator (==), as the latter will convert the two values to a common type before checking equality, which is not what we want.

At this point, we’ve gone over all the tools you’ll need to write the booWho function, so if you’re working through the freeCodeCamp curriculum you may want to go try to solve it on your own, otherwise, read on…

Spoilers_ahead

Here’s the solution to ‘Boo who’ that I came up with:

As you probably know, || is the logical operator ‘or’ in JavaScript, so this function will return true if bool equals true or false.

The freeCodeCamp wiki provides an even shorter solution using the ‘typeof’ operator, written by Rafase282.

Both solutions solve the ‘Boo who’ algorithm challenge and pass all the test cases at freeCodeCamp.

That’s it for now, hopefully this helped straighten out the code…

-Jeremy