Active vs Passive Learning – What’s the best way to learn to code?

So, you’re learning to code…   When you sit down at the computer, do you open an online course?  A book?  An IDE and start hacking away?

After all, what is the most effective and efficient way to learn to code?

We live in exciting times and the ability to code can open a lot of doors. Never before have so many top notch resources been so readily accessible to anyone willing to roll up their sleeves and dig in.

So, what is the best way to learn to code?

Learning to Code Strategies

The way I see it, there are two main strategies for learning to code.

One strategy, passive learning, involves the consumption of resources.  By this I mean reading books, websites, and other blogs, or watching tutorials on Udemy, Coursera and YouTube.

The second, active learning, involves lots of practice.  This can include building side projects, working through the freeCodeCamp curriculum or writing solutions to algorithm challenges at sites like CodeWars or HackerRank.

Which is best for learning to code, active or passive?

The answer, in my opinion, lies somewhere at the intersection of these two strategies.

I know, way to take a stance, right?  Let me explain…

If you stick with the passive phase until you feel that you’ve learned enough and are comfortable enough to start coding on your own, chances are you’ll never get to the active phase.

On the other hand, if you sit down and just start hacking away, not having taken the time to learn the basics, what exactly are you going to hack?

The Iteration between Watching and Doing

In my experience, learning to code is a very iterative process.  Consider the following as what I think might be a typical ‘learn to code’ journey.

After learning some of the basics, you gather your courage and start building something of your own.

Shortly after you begin writing your own code, you hit a wall. At that point, you go search for a solution on MDNStack Overflow or any of the other great resources out there.

Once you have a solution, you go back to the project with your newfound knowledge and make your way past the previous barrier.

Until you hit the next wall. Back to Stack Overflow…

Rinse and Repeat…

Passive then Active…

Over and Over…

Get the point?

In my humble opinion, iterating between learning and doing while building something of your own is the best way to learn to code, but let’s back up a bit.

When do you know enough to cut the cord from the learning material and make that original leap into your own project?

When to Make the Leap

I’ve given this question a lot of thought lately with how it relates to my own situation…

I’ve been learning Angular over the last several months while working my way through the Free Code Camp data visualization and back end sections.

I started with Angular by doing some reading, then enrolled in this Udemy course. Max is an excellent teacher, by the way, and I highly recommend the course.

The problem is that there are 248 lectures and over 16 hours of content! Considering that I coded alongside the examples in the course and took copious notes (not to mention my full time job and two kids!), this course would take me forever to get through.

After spending a few weeks working my way through most of the course and it’s examples, I started wondering – “do I know enough to try to build something??” It turns out, no, I really didn’t…

It wasn’t that I didn’t know Angular in enough depth. You don’t necessarily need to know something in great depth to get started, that’s where the iteration between active and passive comes in.

The problem was that I didn’t have the breadth of knowledge to start on my own. I had a hard time moving from the active phase to the passive phase because I didn’t know what I was looking for.

This led me to come up with the following guideline to use in the future – “Try to know what you don’t know before you starting on your own…”.



via GIPHY
I know, sounds pretty asinine right?  Let me try to explain with an example…

How can you possibly “know what you don’t know”?

Let’s return to the Udemy course example.

I had worked my way through the components, data binding, directives, services and forms modules of Max’s course. Of course, I didn’t know everything about implementing these topics off the top of my head, but at least I had a general idea about how they each worked.

In other words, I generally knew what I didn’t know about them. That way, when I encountered a problem, I knew where to start digging for a solution.

I had not, on the other hand, looked at the HTTP section of the course. So when I had to make an API call in my Angular app, I didn’t know there was a mechanism in Angular to handle this.

So I turned to something I already knew… I tried setting up a jQuery.ajax() call, not knowing that Angular had their own HTTP service.

Had I at least glanced through the HTTP module, I would have learned enough to know it existed, and therefore would have turned to it to make my API call.

The Take-Home Lesson

My point here isn’t that I’m an idiot for trying to set up $.ajax() in an Angular app. Although if the shoe fits, right??

My point is that I would have been better off if I had gotten a broader understanding of Angular before I had begun. I didn’t need to know exactly how the Http service worked, just that there was one, and therefore, would have known where to turn to make that API call.

To sum it all up, in the unlikely event that anyone is still reading, the passive phase is great for exposing yourself to the breadth of a topic (concepts, ideas, etc), whereas the active phase will really hammer home the knowledge and give you a deep understanding of what you are learning.

The trick is finding the sweet spot where these two intersect.

I hope you were able to take something away from my musings, please feel free to comment below either way.

-Jeremy

Learning to code? Avoid Workload Paralysis

There’s a lot to consider when learning to code.

A LOT!

In fact, saying “there’s a lot to consider” is a huge understatement. Chances are, at some point you are going to get overwhelmed with trying to find the best path forward.

With that overwhelmed feeling comes the sense of workload paralysis. You know, that feeling where you have way too much on your plate and you can’t possibly picture a way to get everything done.  So you just sit there, shut down and stare at your monitor like a deer in headlights…

Sound familiar??

The Triggers

This has happened to me several times while on this ‘Learn to Code’ journey and in looking back, I’ve identified two main triggers for it…

Either a) I’ve read the opinions of too many people, each giving different advice on how to approach learning to code or b) I’ve let my mind to wander from the task at hand and allowed the big picture overwhelm me.

Granted, these are what I’ve identified as my triggers. Yours could be different, so it might be worth a little time reflecting on the situations that send you into paralysis.

For the time being, let’s dig a little deeper into mine…

The Trap of Too Much Advice

Reading advice is a good thing, it can help you navigate your journey more efficiently. But taking advice from too many people, all with opposing views can be paralyzing.

Or worse, you’ll start resembling this cat trying to catch a laser pointer.

via GIPHY

That could get ugly pretty quick… But what to do about it?

Make it your mission to find someone whom you trust, and who is offering advice on the exact goals you have set out for yourself. Doing this will keep you focused on your own path, not someone else’s…

Use this advice to draw a path forward and trust that if you maintain that path, you’ll eventually reach your goals.

Most importantly, write the plan down.  I’ll discuss this more below, but if you try to keep this all in your head you’re destined to become that cat…

The Big Picture

Don’t get me wrong, I’m not saying that you shouldn’t have perspective of the big picture.  But if you allow it to overwhelm you, you’ll lose sight of the path you’ve have carved out for yourself.

As I mentioned above, use the advice of someone you trust to create a plan.  A key part of this, is writing it down and approaching it in a step by step manner.

All you really need for this is a pen and a piece of paper, but if you prefer to keep a digital copy, Trello or even Google Docs are decent options (yes, I know there are plenty of storyboard and goal writing apps out there, but that’s beyond the scope of this article).

Once you write everything down, you no longer have to spend the mental bandwidth on remembering the entire plan.  You can clear your head and focus on the next step.

Again, allow yourself to look at the big picture but ALWAYS keep your focus on the next small task in order to maintain momentum on your path forward.

As alway, I hope this was helpful, feel free to leave comments below.

Now go build something awesome!!

-Jeremy

Deployment of Angular2 App to GitHub Pages

Angular 2, or just Angular as it’s now called, is new, exciting and constantly evolving.  While it’s great to be on the cutting edge of a JS framework, the process can be extremely frustrating at times…

I’m currently working through “Angular 2 – The Complete Guide“, an Udemy course by Maximilian Schwarzmuller.

I wanted to take a quick break to test how much of the course has sunk in, so I went back and rebuilt my Random Quote Generator App from the Free Code Camp frontend projects.  I picked this because it was fairly simple and I wanted to build an Angular project from creation to deployment without investing too much time.

Building the project was relatively quick and painless, which is a testament to Max’s course mentioned above.  You can see my GitHub repo here (and the app finally deployed here).  Given that it’s a static app (i.e. no backend), I figured GitHub pages would be a good place for deployment.

This is where the headache started…  One of the inherent problems when working something like Angular, that’s constantly changing is that many of the resources become irrelevant and incorrect very quickly (this one, no doubt, included).

I found multiple blogs and Stack Overflow answers, some written only months ago, claiming that you could deploy to GitHub pages with the following one command:

After much frustration, and multiple attempts at rebuilding and redeploying, I found that the deploy command was removed from the angular-cli.

So the command written above certainly wouldn’t work.  The functionality, however, is available through the angular-cli-ghpages npm package.

Before we proceed on how to use the angular-cli-ghpages package, there are a couple assumptions being made in this process that will need to be met if this is going to work…

First, I’m assuming that you have Node.js installed on your computer.  If not, visit the Node.js site for instructions for download.

I’m also assuming that you have an Angular app, associated with a GitHub repo, written and ready to deploy…  If not, go create something and commit it to GitHub!!

With those assumptions out of the way, input the following in a terminal to install the npm package globally:

Once installed, you’ll need to build the app.  In the app’s folder, run:

This will create a dist folder that contains the compiled code for your app.  Obviously, you’re going to want to change the above command to include your GitHub username and the repo name.

Then deploy:

or just:

You can find all the options at the angular-cli-ghpages site.

This will deploy a new branch to your GitHub repo called gh-pages branch. Make sure you’re using this branch as the source for your app.  You can find/change this option under the GitHub Pages section of the Settings tab of your repo.

It might take a few minutes for the app to show up on your page, be patient!

That’s it for now, I hope this was able to help.

-Jeremy

Prefer Heroku?  Here’s a good article if you’re having trouble deploying a static angular app to heroku.  The title says Vue, but it works great for angular now that they’re using webpack…

The MEAN Stack – A New Direction for Crooked Code!

It’s been about 8 months since I began the Crooked Code blog…  And so far it’s been a great experience!

While the overall purpose for writing the Crooked Code blog has been, and will continue to be, helping others learn to code, most of the posts fall under one of two major themes…

The first of these themes has been articles covering Algorithm Scripting Challenges in the Free Code Camp curriculum. Two of the most popular of these posts, based on pageviews, have been Symmetric Difference and Map the Debris.

The second major theme has been tutorials on JavaScript, including the Rubber Ducking Series I started a couple months ago based on (but not affiliated with) ‘You Don’t Know JS’.

Where to go from here??
Where to go from here??

While I plan to continue adding JavaScript tutorials, particularly the Rubber Ducking Series, I’m planning on putting a temporary hold on new posts covering Free Code Camp algorithms.

As you may have heard, Free Code Camp has announced they are adding a major expansion to their curriculum. A look at the current map of the beta version shows that many of the advanced algorithms will be supplemental to the main program.

Because of this, I’ve decided to wait until the beta is released into production before I continue writing up more algorithm challenges, as I have no way of knowing which challenges will make the final cut.

I am, however, very excited to announce that I’ve decided to add a third major theme here at Crooked Code – Angular 2 (ng2) and the MEAN stack.

Angular 2

I’m doing this for several reasons…

First, about 90% of my focus lately has been on learning Angular 2.  It’s the first JS framework I’ve learned, so the process has been a long one, and judging by many of the comments I’ve seen throughout the FCC community, I’m not the only one on this journey.  Which brings me to my second reason…

The final release of ng2 is so recent, many of the tutorials and videos out there are a mix of earlier release candidates and the final release all mashed together…

This causes some major confusion in building a working ng2 app, particularly in how to structure the project.  So I hope to shed some light on what I’ve found and save others some of the time I’ve spent (and continue to spend) making sense of it all.

MongoDB, express, Angular2 and NodeJS
MongoDB, express, Angular 2 and NodeJS

Further, I plan to highlight how the ng2 frontend framework ties into the rest of the MEAN stack.

Now that I’ve spent some time digging into Angular 2 on a deeper level, I’m planning on using my previous experience with Node, Express and MongoDB (with Mongoose) to build larger full stack apps.  I think this will be a great opportunity to share what I’m learning with the Crooked Code community.

That’s all for now,

-Jeremy

 

 

Block Scope and Hoisting – An Exercise in Rubber Ducking

This is a follow up to  ‘Intro to Scope’, previously posted here at CrookedCode.  It’s part of our rubber ducking series, where we’re attempting to work through some of the more difficult parts of JavaScript using Kyle Simpson’s book series, You Don’t Know JS, as a guide.

If you want to know more about the project, check out this post.  If you’re thinking to yourself “Where does this guy get off thinking he can explain this stuff better than Kyle Simpson?”, check out the disclaimer here. Otherwise, read on…

As the title suggests, this post will cover block scope versus function scope, particularly as they pertains to varlet and const. I’d like to start with the concept of hoisting, however, as I think it’ll help understand the rest of the article.

WTF is Hoisting?  (And Do I need a boat to do it?)

Consider the following:

The question here is will “Will this get logged?” actually get logged to the console even though hoisted is declared after it  A) has a value assigned to it and B) gets logged.

The answer is yes, “Will this get logged?” is logged to the console.

You’ve also probably seen examples of functions getting invoked before they’re even declared.  Have you wondered why that works too…

Something like:

The above snippet will log ‘Henry’ to the console.

Both of the above examples work because of hoisting.  As we mentioned in the previous article, JavaScript is a compiled language.  Part of the compilation step is finding all the declarations (variables and functions) and associate them with the appropriate scope.

This part actually occurs first, before the code is executed.  Therefore any function or variable declared in a given scope will be available throughout that scope.

In the first example above, var hoisted would have been ‘hoisted’ to the top of scope within the hoist() function.  So when the JS engine comes across hoisted = a and searches for a variable called hoisted in the lexical scope within the hoist() function, it’ll find it!

One more note on hoisting…

Don’t confuse declaring a variable with assigning a value to a variable, even if that happens in the same line of code.

var name = 'Henry'; is seen as two statements by the JS engine, var name; and name = 'Henry';. The declaration is hoisted, the assignment is not…

If you think this is just semantics, consider the following:

Someone with a tenuous grasp on scope might look at this snippet of code and think there are a couple possibilities…

“That’ll probably be a ReferenceError because a is declared after it’s logged..”

Nope…

or if they’ve heard of hoisting….

“Maybe it’ll print ‘Henry’ to the console because a is hoisted within the printYourDogsName function”

Nope again…

The actual answer is that the snippet logs undefined.  If you think back to the last article, undefined (as opposed to ReferenceError) means that the JS engine found the variable a (because it was hoisted), but a was undefined (because the a = name assignment didn’t happen until after console.log(a).

Ok, enough about hoisting… I think that should give us a pretty good grasp on how things work.  For more detail please refer to YDKJS.

The Complexity of Scope

I hope my previous article, along with what’s covered here, has given you a pretty good understanding of lexical scope and how it works in JavaScript.  So why did Kyle Simpson feel the need to devote an entire book to scope and closures?

You know the old saying ‘You don’t know what you don’t know…”?  Well, there are several special circumstances that are covered in ‘Scope and Closures’ that I won’t be addressing here at Crooked Code of which you should be aware.

One such concept is using scope to hide access to variables.  I plan to touch upon some of this in a future article on Modules, but in the meantime, YDKJS covers it here.

You can also read about the specifics of scope as it pertains to function expressions, including Immediately Invoked Function Expressions or IIFEs, here.

The final topic you should be aware of that I won’t be covering in this article is closure.  Simpson devotes an entire chapter to closure and I highly recommend reading it.

I’ve read it a couple times and my pulse still quickens a bit when someone mentions closure (I’ll be writing a rubber ducking article here on closure in the near future to solidify the concept in my own head).

Now on to Block Scope

We’ve discussed previously that JavaScript uses functions to define scope.

This was, for the most part, entirely true until ES6.  Among the changes in ES6 were the keywords let and const, which provide us ways to declare variables with block scope.

The only difference between the two is const declares a constant, which can’t be changed once assigned a value.

Before we get into what block scope is, there’s a key note to remember when dealing with let and const.  They are NOT hoisted within their block of scope.  This means that you must declare them before you use them or it will result in a ReferenceError.

Now, what’s block scope?  Simpson tells us a block is commonly a {...} pair. So think for loops, if statements, etc..  You can even create your own block of scope by enclosing code in curly brackets.

Block scope can be useful in several key ways…  Consider the following:

In this example, as I’m sure you can figure out by now, 10 (not 42) would get logged to the console.  This is because i would be hoisted to the scope within the redundantI function.  So when the engine comes across the var i = 0 statement in the for loop, it will already see the i variable and use that one.  Now consider:

This snippet would actually result in 42 getting logged.  Why? Because let created a new i variable for use ONLY in the for loop!

I realize this example is pretty idiotic and you’re probably thinking to yourself “This guy is effing nuts… I’d never make that mistake in my code…”.

I know you wouldn’t make a mistake like that, but think about functions that are 100+ lines of code with a couple additional functions nested within.

If you’re using a variable for the sole purpose of controlling the for loop, wouldn’t you prefer to keep it out of the overall scope? Wouldn’t it be nice if you could use the variable in the loop, then have it go away?  let enables that…

Simpson also discussed using block scope to enable garbage collecting when you’re handling large amounts of data.  It’s a pretty interesting concept and can be read in the garbage collection section of Chapter 3.

The final point to mention regarding the use of let concerns its use in loops.  Simpson points out that, not only does let bind the variable to the body of the for loop, but it re-binds the variable to each iteration of the loop.

This may seem trivial, but when you consider closure it can be a very useful behavior if you understand it enough to use it properly.  I’ll cover this in more detail in my article on closure, but you can read about it now in the YDKJS section called ‘Block Scoping Revisited’.

That’s it for now…  If anyone’s still reading, thanks for taking the time.  I hope I was able to straighten out the code for you.

-Jeremy

Intro to Scope – An Exercise in Rubber Ducking

As I stated previously, I’ll be writing a series of posts attempting to explain, or rubber duck, some of the more difficult topics in the You Don’t Know JS (YDKJS) series by Kyle Simpson.

Before you start screaming at me that Kyle Simpson has forgotten more about JavaScript than I ever knew, to which I would wholeheartedly agree, please read the following disclaimer…

Disclaimer:

I have great respect for Kyle Simpson, his method for teaching and the YDKJS series.  This series of posts were not endorsed by Simpson and are merely an attempt to supplement his books.  This project is being created for the sole purpose of helping to solidify these concepts in both your mind and mine.  If you are learning to code in JavaScript, I highly encourage you to read the YDKJS series.

What is Scope?

Variables are extremely important to computer programming.  They allow us to write complex and dynamic programs.

But how and where should we create variables? How and where do we store them?  And, maybe most importantly, how and from what part of the program are we able to access a particular variable?

Each language has very specific rules for these questions.  These rules can be thought of as Scope.  Here we’ll introduce the rules of scope specific to JavaScript.

Given that scope is a fairly broad topic, with many different aspects to cover, I think it best to break this into multiple blog posts.  The goal here will be to introduce the topic of scope and provide a foundation that we can build upon in later discussions.

What we cover here can be found in far greater depth in the 2nd YDKJS book – “Scope and Closures”.

Let’s begin by taking a step back…

JavaScript is a Compiled Language (surprise!!)

For those who have worked with more traditionally compiled languages like C++ or Java, it may come as a bit of a surprise that JavaScript is actually compiled before it runs.  This misunderstanding is likely because, unlike many other languages,  JavaScript is compiled just before run time rather than in an entirely different build step.

Right now you may be asking yourself why this is relevant to a discussion on Scope…  That’s a great question, let me try to explain.

Simpson describes that, at a very high level, the 3 basic steps in compilation are 1) tokenizing/lexing, 2) parsing and 3) code-generation.

The tokenizing or lexing step breaks up strings of characters in your code into chunks (tokens) that are easier to understand.  Next, the parsing step takes all these tokens and forms a tree of nested elements called an Abstract Syntax Tree. This tree represents the grammatical structure of the program.  It is from this AST that code is generated in step 3.

Still not clear on how this relates to scope, right?

To clear this up, you must understand that JavaScript employs lexical scoping rather than dynamic scoping.

This means that the scoping for a program is determined at the time of lexing, based on where the variables fall within the blocks of scope. Therefore the author is able to control the scope at the time he is writing the program without worrying that the scopes will change at run time.

This is a key concept in understanding the behavior of scope.  For more detail, please read the first 2 chapters in  “Scope and Closures”.

As with most rules, there are exceptions….  Simpson discusses several ways to change lexical scoping at run time.  This can be accomplished using eval() and with(), both of which he frowns upon using.  I don’t plan on going over these here, but you can be read about them in Ch. 2 .

General rules and behavior of scope in JavaScript

Generally speaking, (and again, there are several exceptions to this rule, which we will likely cover in later posts) JavaScript derives its scope from functions.

What does this mean?

You can think of scope as a series of boxes contained within each other. These boxes contain the functions and variables that are declared within that function.  This structure enables control over how one block of scope is allowed to access another.

In JavaScript, there is a scope (or box) that contains the entire program, called global scope.  Each time you create a new function, a new scope box is created.  This new scope will contain any new variables or function declared within (including any parameters declared in the function definition).

And so on, and so on, as functions continue to be nested within other functions…

Mentally, you can picture scope as something like this:

A group of nested boxes meant to depict the concept of scope.
The numbers are included only for reference and should not be used to infer relationships between blocks.

When you reference a variable within a JS function, the current scope will be searched.  If the variable is found, great, that’s what will be used.  If it isn’t found, the JavaScript engine will continue to search the scope boxes incrementally outward.  The first match it comes across will be used.

Let’s use the model depicted above…  Let’s say the function for scope #5 referenced a variable called ‘foobar’.  If ‘foobar’ was not found in scope #5, the JS engine would then search scope #3.  If not found in #3, it would search #2, then #1.  Scopes #6 and #4 would not be searched.

What happens if the JS engine reaches the global scope and is unsuccessful in finding ‘foobar’?  The answer to that depends on what you are trying to do with the variable.

LHS vs RHS References

Simpson describes two scenarios for referencing a variable.  He calls them LHS (Left hand side) or RHS (Right hand side) references and they are handled differently in the case of an unsuccessful lookup.

While LHS and RHS refer to which side of the assignment operator (=) the variable is found, this shouldn’t be taken literally, as there are multiple ways to assign a value to a variable.

Rather, think of the difference as such…  LHS is a lookup where we are trying to assign a new value to the variable, whereas RHS is merely looking up the value of the variable to use within your function.

Let’s look at an example:

First, let’s go through this code, find the variables and decide in which scope they reside. There are 2 distinct blocks of scope here.  The global scope and the scope inside the addOne function.

There’s only 1 variable in the global scope and it’s the function addOne. The scope nested inside the addOne function contains 2 variables, sum and a.

Now, where and how are these variables referenced?

There are 2 references to each variable in the addOne function.

Line 1 contains an LHS lookup for a.  It’s LHS because we are assigning the value of 9 to the variable a when the function is called.  Then there is an RHS lookup of a in line 2, as we are only looking up the value of a to use in a+1 (the value of a will not change as a result of this reference).

There’s also one of each type of reference to sum.  The LHS reference to sum is on line 2, where we are assigning the value derived from a+1 to sum.  The RHS reference to sum occurs on line 3, where we lookup and log its value.

The last lookup is on line 6 where we perform an RHS lookup to addOne by invoking the function.

Note: Originally, I mistakenly assumed there was also an LHS reference to addOne on line 1 when we declared the function.  Simpson states in ch. 1, however, that due to the way the compiler handles function declarations, it would be wrong to think of them as LHS references.  Please see YDKJS for further clarification.

RHS… LHS…  Why does it matter?

You may be saying to yourself RHS… LHS… ABC…  XYZ…  Who gives a $*&# as long as I have access to my variable…  The distinction comes when the engine is unsuccessful in finding the variable for which it’s looking.  Knowing the difference now might save you a loooong time in debugging later.

So, what is the difference between an unsuccessful RHS vs LHS lookup? The difference lies in how the engine handles them.

When the engine is unsuccessful in an RHS lookup it throws a ReferenceError.  If the engine does find the variable, but the program is trying to do something with the variable that doesn’t make sense (i.e. invoke as a function a non-function variable), the engine will throw a TypeError.

LHS lookups, on the other hand, are a different story.  If the engine is unsuccessful in an LHS lookup, it simply creates the new variable in the global scope and hands it back to the engine.  As you can imagine, this can lead to all kinds of headaches.

You can prevent this by running in strict mode with "use strict";.  An unsuccessful LHS lookup in strict mode will result in a ReferenceError, similar to that of an unsuccessful RHS lookup.

Let’s look at some examples…

Let’s say we make a typo on line 3 when we are logging sum and mistakenly write sums.

Getting a ReferenceError: sums is not defined tells us that we tried to reference a variable named sums that we failed to declare in a relevant scope.

Another example… Let’s say we try to invoke something that isn’t a function.

Again, the error we get tells us exactly what we should be looking to fix.

Now for an LHS example.   Consider the following:

You can see here that 10 is logged to the console.  Even though we didn’t declare sum as a variable, the engine went ahead and created it for us and the function completed without an error.

What about strict mode?

We can see here that strict mode prohibited the creation of an undeclared LHS reference.

As you can see, knowing the rules of scope and how errors are thrown can significantly cut down your troubleshooting time.

 

I am the scope master!!

Ok, that was a lot to take in, but seemed pretty straightforward.  Is there more to learn on scope or am I now a scope master?

Settle down Yoda…  There are some more advanced topics on scope that I plan to cover in a future post, such as function expressions, IIFEs, hoisting, block scope and the use of let and const.

There are also scope closures to discuss…  I’m not exactly looking forward to writing that one, as closures can be pretty damn confusing.  But, hey, that’s what these rubber ducking exercises are all about, right?

I hope you found this helpful, feel free to leave your comments below.

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

-Jeremy

 

FCC Advanced Algorithm Scripting Challenge – No Repeats Please

There are a couple algorithms that are consistently asked about in the FCC forums because people are having trouble coming up with a solution. ‘No Repeats Please’ is definitely one of them…

No Repeats Please

In my opinion, the best place to start any of the algorithm scripting challenges is making sure you completely understand the problem.

Here is the challenge as stated by FCC:

Return the number of total permutations of the provided string that don’t have repeated consecutive letters. Assume that all characters in the provided string are each unique.

For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (abaand aba) don’t have the same letter (in this case a) repeating.

Ok, not exactly the clearest of problems…  In my opinion, there are two concepts in this algorithm that add to the difficulty.

First, we’re going to have to understand what permutations are and how to find all of them for a given string.  Once we have that, we’ll need to write a regular expression (regex) that looks for repeated letters in each permutation.

Let’s get a better understanding of each of these concepts before we attempt to solve the algorithm challenge.

What are permutations?

The wikipedia page on permutations is a pretty good start if you haven’t been exposed to permutations previously.  It states:

In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting.  These differ from combinations, which are selections of some members of a set where order is disregarded.

The key takeaway from this should be that a permutation involves all the members of the set and the order matters.

Part of the given problem states that we should ‘assume that all characters in the provided string are unique’.  This means that for the given example, ‘aab’, the first two letters should be considered unique even though they are both the letter ‘a’.  Therefore, the two permutations without repeats, ‘aba’ and ‘aba’, are considered unique and we must count each of them in the solution.

A quick side note… If you’re looking for further clarification as to the difference between a permutation and a combination, this website does a good job comparing the two…

How can we find all permutations of a string?

Permutations are prevalent throughout many areas of mathematics and computer science.  It should, therefore, be no surprise that there is a well known algorithm, called Heap’s Algorithm, that will find all the permutations for a set of objects.

Heap's Algorithm
Heap’s Algorithm at work

Keep in mind, there are n! number of permutations for a set of n objects.  So for a string of four letters there are (4 x 3 x 2 x 1) or 24 unique permutations.

Consequently, Heap’s algorithm works on the order of O(n!), the slowest order of functions.  Therefore, as the set gets larger, increases of even one number will cause the algorithm to slow drastically.  To put that into perspective, a set with 15 elements, will have over 1.3 Trillion permutations.

Ok, enough about the theory of permutations, how do we implement Heap’s algorithm?

Heap’s Algorithm

At this point, I’ll only post the pseudocode for Heap’s Algorithm found in Wikipedia, in case there is anyone reading this who is trying to solve ‘No Repeats Please’ and wants to attempt to implement in JavaScript on their own.

Given this isn’t a post specifically about Heap’s Algorithm, I’m not going to go into depth about how it works.  Suffice to say that it systematically switches one pair of elements in each step, eventually yielding every possible permutation.

I encourage you to walk through the algorithm until you understand the workings ‘under the hood’.  The image to the right shows the order of the elements after each iteration of Heap’s Algorithm for a set of 4 elements.

Here is the psuedocode for the recursive version of Heap’s algorithm.  If you prefer to implement non-recursively, there is a version on the algorithm’s  Wikipedia page.

Let’s move on to regular expressions before we put everything together in the final algorithm.

Regular Expressions (RegExp)

In JavaScript, regular expressions are objects used to describe patterns of characters in text.  They’re extremely useful when solving certain problems IF you know how to use them.  That’s a big if, because they are very unintuitive to use and a weakness of many beginner programmers.

w3schools shows the syntax of regular expressions as /pattern/modifiers; .  Rather than diving down the rabbit hole of regular expressions, I’ll point out some great resources to learn regex, then write and explain the one we’ll need to solve this challenge.

MDN is a good intro and explains most of what you’ll need for this challenge.  For further learning, Eloquent JavaScript has an entire chapter on regular expressions.  This site will let you practice writing them, and if you’re feeling really ambitious, although I haven’t read it, Mastering Regular Expressions was highly recommended by multiple people on the FCC forums.

A Regex for Repeating Letters

Let’s build a regex that will recognize repeating characters.   We’ll start with /[a-zA-Z]/, which will match any and every letter in the string.

Patterns in parentheses are remembered and can be referenced in order (i.e. the pattern in the first set of () can later be referenced as \1 , the second as \2  and so on). Therefore, adding parenthesis like so, /([a-zA-Z])/, causes the letter that is matched to be remembered.

Next, adding \1 after ([a-zA-Z]) will cause the regex to look for a repeat of whatever the ([a-zA-Z]) matched (i.e. a pair of the same letter), which is what we need!

Therefore, our regex for finding a repeating letter is going to look like this /([a-zA-Z])\1/  .

Crystal clear right!!

An Additional Note on Regular Expressions

It’s important to note regular expressions are objects in JavaScript and inherit the methods associated with the RegExp prototype.

To solve ‘No Repeats Please’, we’ll be using the RegExp.test() method.  When the test method is passed a string, it will return a Boolean telling you if that string contained the pattern.  So /([a-zA-Z])\1/.test(str) will return true if there are repeating letters in str.

Structuring the Algorithm

Now that we have a better idea of the problem, we can start thinking about how to solve it…  There are a couple ways we can structure this algorithm.

One, we could use Heap’s algorithm to iterate through all permutations of the given string, pushing each onto an array.  Then, having an array with all permutations, we could check each element of the array for repeats.

Or two, we could use Heap’s algorithm to iterate through all permutations, each time checking for repeats and if not found, increment a counter.

I chose to write it the second way with efficiency in mind.  Given the function is on the order of O(n!), we don’t want to iterate through all permutations to create the array, then iterate through again checking for repeats.

This won’t make much of a difference for strings of length 5 or 6, but it will make a huge difference on longer strings.  In fact, to demonstrate this, I tested the function written both ways.

When running the function the first way (iterating twice), a string of 10 characters took 3523ms vs 2287ms for a function written the second way.  When I increased the string to 11 characters it took the second function 26,802ms while the first function failed due to lack of memory.

Now that we have a structure in mind for the algorithm, let’s finally go ahead and write it!

My Solution to ‘No Repeats Please’

If you want to take a stab a writing the solution on your own, now’s the time…  I’m going to post the solution that I came up with below.  Again, there are multiple ways to solve this algorithm challenge, this is just the one that I came up with.

Spoilers_ahead

If you were having trouble with ‘No Repeats Please’, hopefully breaking it down like this helped.  This is definitely one of the hardest of the FCC algorithm challenges.

I hope you found this post useful…  If so, feel free to leave a comment and let me know. Thanks for reading, that’s all for now…

-Jeremy