Week 2 at Hack Reactor LA: Javascript Inheritance and N-Queens

This week, we continued with more fundamental concepts of programming with Javascript and explored topics like object inheritance, ajax requests, and recursion with the infamous n-queens problem. I’ve really started to adjust to the time commitment of the program and have found it easier than expected to have enough energy to absorb the material effectively. The course moves quickly, but so far not too quickly that we’re unable to keep up. Here are a couple of nifty things I learned this week.

Object.create vs new

This is probably a subject that deserves its own post, if not its own little e-book. I was never truly 100% sure on what the difference was between them. I had mostly used the new keyword and never bothered to learn when to use Object.create when setting up prototypes. Here’s an example of when it is appropriate:

SmartPhone.prototype = Object.create(Phone.prototype);
SmartPhone.prototype.constructor = SmartPhone;

Say you’re trying to create a SmartPhone object which is a subclass of a Phone class. This is a typical linking of the prototypes that we use in pseudoclassical instantiation. Is there a difference than when we link them like this?

SmartPhone.prototype = new Phone();
SmartPhone.prototype.constructor = SmartPhone;

I was surprised to find out that indeed there is. The main difference is that the new keyword creates the “this” object, invokes the constructor, and returns the created “this”. This may be problematic if, for example, the constructor relies on parameters that are passed in and we don’t pass in any. Therefore, when we don’t want to actually run the constructor function, and just want to link the prototypes, is it better to use Object.create.

N-Queens

The second interesting problem I faced this week was with the infamous n-queens problem. It asks for you to write an algorithm to solve all the solutions of how you could place an n number of standard chess queens on an N x N board. My partner and I were able to do so with a recursive algorithm, but found our algorithm to be quite slow when calculating at higher N’s.

This sprint taught us a lot about recursion and time complexity. For most of the second day, we focused on optimizing and speeding up our algorithm. Our biggest breakthrough came when we analyzed the helper functions we used and realized it made needless checks for queen attacks. When we eliminated them, our code sped up 20x instantly. Simplifying recursive code, which usually has a quadratic time complexity has a huge payoff. It’s a nice thing to keep in mind when writing recursive algorithms in the future.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.