Javascript: Some vaguely interesting interview questions

There’s plenty of opinions about the efficacy of technical interviews and an equally large amount written on the topic. Personally, I don’t think there’s much value in putting someone in front of a whiteboard and seeing if they can regurgitate how merge sort works (I couldn’t) and there’s plenty of blog posts arguing that point. Something that I do think is valuable is trying to gauge how well someone really knows a language that they’ve listed on their resume or used in a project. And recently, with the surging popularity of Node.js and “coding boot camps” it seems like every resume we’ve seen mentions a proficiency in Javascript.

So how could you suss out someone’s knowledge of Javascript? I poked around on Quora a bit and ran across few top voted related questions: What are some good JavaScript interview questions? and What are the most important JavaScript concepts to know for a job interview?. Skimming through them know, the questions are mostly focussed on “tricks” which isn’t very useful and the list of skill is a bit underwhelming as well. Ok, so what questions can we ask?

Prototypical Inheritance

Prototype based inheritance is woven into the fabric of Javascript so I think chatting about it will reveal a lot about a candidate. You’ll get a sense if they generally “get” how object oriented programming works and then more specifically how Prototype inheritance in Javascript works.

Looking at code, a good starting point would be talking through the difference between “Duck” in the following sample:

// A duck
var Duck = {
    quack: function(){
        alert("quack!");        
    }
};

Duck.quack();

// Another duck
var Duck = function(){};

Duck.prototype.quack = function(){
    alert("quack!");
};

(new Duck()).quack()

From there, there’s the natural philosophical discussion about how Javascript doesn’t have classes but instead objects are copied from existing ones down the prototype chain. That seems to naturally lead to a discussion of how you’d accomplish something like (don’t in production):

var list = [1, 5, 7];
console.log("Has all evens? " + (list.hasAllEvenNumbers() ? "Yes" : "No"));

First Class Functions and this/bind

First class functions are heavily used Javascript in idiomatic Javascript so they certainly deserve some discussion. At a high level, describing first class functions is fairly simple. Functions are treated like any other object so that they can be passed as arguments, inserted into arrays, and all the other things you’d normally be able to do with objects.

Jumping back into code. An interesting first discussion would be “How could you implement a switch statement without using ‘if’ statements or a ‘switch’ block?”

// With a switch
var key = "goose";
switch(key){
  case "duck":
    alert("no dice");
    break;
  case "moose":
    alert("tardy moose");
    break;
  case "goose":
   alert("money!");
  break;    
}

// Without one
var key = "goose";
var fns = {
  "duck": function(){ alert("no dice"); },
  "moose": function(){ alert("tardy moose"); },
  "goose": function(){ alert("money!"); },
};

fns[key].call();

Getting a bit fancier, another task would be to implement a “filter” method similar to the one found in lodash/underscore. “filter” accepts an array of elements and a callback and returns the elements which return “true” when passed to the callback. So as an example:

var list = [2, 4, 7];

var final = filter(list, function(){return this % 2 == 0;});

// final = [2, 4]

The big change is in our “filter” we’re changing the semantics so that “this” is the value from the list being filtered. Watching how someone approaches and implements this will reveal how deeply they understand Javascript’s function semantics.

Async and Promises

Last up would be touching on Javascript’s model of asynchronous programming followed by a Promise implementation (q, jQuery, etc.). The difference between asynchronous code and synchronous code is large enough that it probably could fuel an interesting discussion. A couple of interesting points to touch on:

  • At a high level, what is the difference between asynchronous and synchronous code?
  • In a single threaded environment like a Javascript engine, why would an asynchronous model be beneficial?
  • Typically, why would an implementation using Promises be more flexible than just a callback?

Jumping back into some code. A good first task would be to execute a set of asynchronous operations in series -

// How would you make these run in series, one after another instead of in parallel?
for(var i = 0; i < 15; i++){
  $.get("http://www.setfive.com");
}

Another interesting task would be to implement a tiny API using regular callbacks and then using a Promises library.

Anyway, just a couple of quick ideas. I’m still new to the recruiting and interviewing game so I’d love any feedback or comments!

Javascript: Mixins in AngularJS

We’ve been doing a bit of AngularJS work (more on that later) recently and true to its reputation there’s an “Angular way” to accomplish most things. Interestingly, one area where I couldn’t find a “one true way” was how to facilitate mixins between controllers or scopes.

Quickly taking a step back, a “mixin” is a form of horizontal reuse that allows two objects to share code without necessarily sharing a common ancestor in an inheritance chain. With concrete examples, you might have a Dashboard and Billing controller which need to share formatting logic but nothing else you’d want to use mixins vs. traditional inheritance. In traditional object oriented language mixins are typically referred to as Traits.

Anyway, back to AngularJS. Let’s say we have some simple logic that we want to share between two scopes:

$scope["selectAnswer"] = function(answer){
  for(var i = 0; i < $scope["answers"].length; i++){
     $scope["answers"][i]["selected"] = answer == $scope["answers"][i];
   }
};

$scope["getAnswerClass"] = function(answer){
  if(answer.isCorrect && answer.selected){
    return "selected-correct";
  }else if(answer.selected){
    return "selected-incorrect";
  }

  return "unselected";
};

# In a template
<a ng-click="selectAnswer(answers[0])" ng-class="getAnswerClass(answers[0])">Answer Zero</a>
<a ng-click="selectAnswer(answers[1])" ng-class="getAnswerClass(answers[1])">Answer One</a>
<a ng-click="selectAnswer(answers[2])" ng-class="getAnswerClass(answers[2])">Answer Two</a>

It’s a contrived example but the “idea” is that you want to share the “selectAnswer” and “getAnswerClass” functions between $scopes of two unrelated controllers. After doing some research, it seems like the cleanest way to do this in Angular is to create a service that contains the functions, inject that into the controller, and then use angular.extend() to add them to the $scope as needed:

function Mixins(){}

Mixins.prototype.selectAnswer = function(answer){
  for(var i = 0; i < this["answers"].length; i++){
     this["answers"][i]["selected"] = answer == this["answers"][i];
   }
};
 
Mixins.prototype.getAnswerClass = function(answer){
  if(answer.isCorrect && answer.selected){
    return "selected-correct";
  }else if(answer.selected){
    return "selected-incorrect";
  }
  return "unselected";
};

// Declare Mixins as a dependency
angular.module("demo")
.factory("mixins", [function(){
    return new Mixins();
}]);

// Use it in a controller
angular.controller( 'DashboardCtrl', function DashboardController($scope, mixins, api) {
  angular.extend($scope, mixins);
});

And that’s pretty much all there is to it. I’m pretty new to the Angular dance so I’d love any feedback!

Javascript: Building a HTML5 canvas puzzle

As promised, here’s the follow up on my previous post Javascript: Using Canvas to cut an area of an image where we looked at how to use Canvas to cut a mask out of an image. To quickly recap, in the last post we looked at how to crop a patterned mask out of an image using a HTML5 Canvas. Using this technique, you’d be able to provide an image that looks something like:

So how do you go about making a puzzle? You can see the end result at HTML5 Canvas Puzzle and the code is online at https://github.com/Setfive/setfive.github.com/tree/master/canvas_puzzle.

As it turns out generating an arbitrary puzzle programatically is reasonably complicated. The best explanation I could find on how to accomplish this is at https://www.allegro.cc/forums/thread/586750/603411#target. Conceptually, the process looks straightforward enough and you could probably manually do it on a whiteboard. Unfortunately, the issue I ran into with this approach is that drawing bezier curves and splines programmatically on a Canvas is a bit involved. I also don’t have a background in vector graphics so I was getting stuck in the weeds drawing lines.

Discounting generating the puzzle entirely on the fly, an alternative approach would be to use a fixed set of available pieces and then “fill in” a grid depending on how large the image area is. Conceptually, the idea is to construct a closed grid of pieces where some number of the pieces can be repeated and then repeat those pieces as needed to cover the target image. The templated pieces I used are in /puzzle_pieces/.

Technically, I decided to use fabric.js to facilitate Canvas interaction along with lodash.js and of course the ubituqous jQuery.

Walking through the code, the steps to build a puzzle are fairly straightforward:

  1. Load images: The first step is to load all the template images and target image so that they’re available to use on a Canvas. Since jQuery is available, one approach is to create a deferred for each image, resolve it as the image loads, and use $.when to wait for all of the images to load. See here for example.
  2. Build pieces grid: Next you’ll need to figure out how many repeated pieces you need to fill into the grid. One issue here is that since the puzzles need to fit snuggly the image dimensions of a given piece won’t be what you need to use to calculate the grid. Because of this, I ended up with a bit of goofy code for this.
  3. Create image masks: Once you have the number of pieces to create you’ll need to cut masks for each piece out of the source image and create fabric.js objects for them. See copyImageChunk.
  4. Place masks: Placing the “pieces” is also complicated because of the dimension issue above. See kludgy code.
  5. Shuffle and track movements: Finally, you just need to shuffle the positions of the images and then track their movement to report a “correct” position.

And that’s about it. One other “trick” is that you can use Window.requestAnimationFrame to avoid locking the UI when you’re creating the masked images since it’s a compute intensive task.

Anyway, as always questions and comments welcome.

Tutorial: Create a HTML scraper with PhantomJS and PHP

This simple tutorial will show you how to create a PhantomJS script that will scrape the state/population html table data from http://www.ipl.org/div/stateknow/popchart.html and output it in a PHP application. For those of you who don’t know about PhantomJS, it’s basically a headless WebKit scriptable with a JavaScript API.

Prerequisites:

1. Create the PhantomJS Script

The first step is to create a script that will be executed by PhantomJS. This script will do the following:

  • Take in a JSON “configuration” object with the site URL and a CSS selector of the HTML element that contains the target data
  • Load up the page based on the Site URL from the JSON configuration object
  • Include jQuery on the page (so we can use it even if the target site doesn’t have it!)
  • Use jQuery and CSS selector from configuration object to find and alert the html of the target element. You’ll notice on line 37 that we wrap the target element in a paragraph tag then traverse to it in order to pull the entire table html.
  • We can save this file as ‘phantomJsBlogExample.js’
  • One thing to note is that on line 24 below we set a timeout inside the evaluate function to allow for the page to fully load before we call the pullHtmlString function. To learn more about the ins and outs of PhantomJS functions read here http://phantomjs.org/documentation/
var page = require('webpage').create();

page.onError = function (msg, trace) {

    phantom.exit();

};

page.onAlert = function( msg ) {

    console.log( msg );

    if( msg == "EXIT" ){
        phantom.exit();
    }
};

page.open(config.url, function(status) {

    page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', function() {

        page.evaluate(function(config){

            window.setTimeout(function(){
                setInterval(function(){
                    pullHtmlString(config);
                }, 2000);
            }, 1);

        }, config);
    });

});

function pullHtmlString(config){

    alert($(config.selector).wrap('<p/>').parent().html());

    alert( "EXIT" );

}

2. Create PHP function to run PhantomJS script and convert output into a SimpleXmlElement Object

Next, we want to create a PHP function that actually executes the above script and converts the html to a SimpleXmlElement object.

  • On line 3 below you’ll construct a “configuration” object that we’ll pass into the PhantomJS script above that will contain the site url and CSS selector
  • Next on line 10 we’ll actually read in the base PhantomJs Script we created in step 1. Notice that we actually make a copy of the script so that we leave the base script intact. This becomes important if you are executing this multiple times in production using different site urls each time.
  • On line 20 we prepend the configuration object onto the copied version of the phantomJS script, make sure you json_encode this so it’s inserted as a proper json object.
  • Next on line 29 we execute the phantomJs script using the PHP exec function and save the output into an $output array. Each time the PhantomJS script alerts a string, it’s added as an element in this array. Alerted html strings will split out as one line per element in the array. After we get the output from the script we can go ahead and delete the copied version of the script.
  • Starting on line 38, we clean up the $output array a bit, for example when we initially inject jQuery in PhantomJS a line is alerted into the output array which we do not want as it doesn’t represent the actual html data we are scraping. Similarly, want to remove the last element of the $output array where we alert (‘EXIT’) to end the script.
  • Now that it’s cleaned up, we have an array of individual html strings representing our target data. We’ll want to remove the whitespace and also join all the elements into one big html string to use for constructing a SimpleXmlElement on line 49.
 public function pullXmlObjBlogExample($siteUrl,$cssSelector){

        //create configuration object containing jquery selector and target site url to pass to the phantom script

        $config = array(
            "selector"=>$cssSelector,
            "url"=>$siteUrl
        );

        //read in the base phantom script and create a copy of it so we don't mess with the original base script

        $templateScript = "phantomJsBlogExample.js";
        $templateFileCopy = "phantomJsBlogExample-copy-".time().".js";

        if (!copy($templateScript, $templateFileCopy)) {
            echo "failed to copy $templateFileCopy";
            return false;
        }

        //Prepend configuration object onto script

        $configObj = file_get_contents($templateFileCopy);
        $configObj = 'var config = ' . json_encode($config,JSON_UNESCAPED_SLASHES). ';' . "\n" . $configObj;

        file_put_contents($templateFileCopy,$configObj);

        //Run the phantom script with php exec function, redirect output of script to an $output array;

        echo exec("phantomjs $templateFileCopy 2>&1",$output);

        //delete the copied version of the phantom script as we don't need it anymore

        if ( !unlink( $templateFileCopy ) ) {
            echo "failed to delete $templateFileCopy";
            return false;
        }

        // The first element of the output will be message about adding jquery and the last element will be the 'EXIT' message from the script,
        // lets remove those so all we have is the html lines

        array_shift($output);
        array_pop($output);

        //remove any whitespace from the array elements and join all the html lines into one string of all the html

        $output= array_map('trim', $output);
        $output = join("",$output);

        //construct an XML element from the html string

        $xmlObj = new \SimpleXMLElement($output);

        return $xmlObj;
    }

3. Call the function and iterate through the SimpleXmlElement Object to get to the table data

  • Call the function from step 2 making sure to pass in the target site url and CSS selector
  • Now that we have the SimpleXmlObject on line 7 we’ll want to iterate through the rows of the table body and pull out the state name and population table cells. It may help to var_dump the entire SimpleXmlObject to get a sense for what the structure looks like.
  • For purposes of this example we’ll just echo out the state name and population but you could really do anything you wanted with the data at this point (i.e., persist to database etc.)
private function scrapePopulationsByState(){

        $cssSelector = "table.sk_popcharttable";

        $siteUrl = "http://www.ipl.org/div/stateknow/popchart.html";

        $tableXmlObject = pullXmlObjBlogExample($siteUrl,$cssSelector);

        $cnt = 0;

        foreach($tableXmlObject->tbody->tr as $tableRow){

            //the first two rows are the header and "All United States" rows so disregard

            if($cnt++ < 2)
                continue;

            //grab the state and population from the corresponding table cell of the row and output!

            $state = (string) $tableRow->td[1]->a;

            $population = (string) $tableRow->td[2];

            echo $state . " has a population of " . $population . "\n";

        }

}

4. Final Output

Finally, running the function from step 3 should result in something like this.

California has a population of 37,253,956
Texas has a population of 25,145,561
New York has a population of 19,378,102
Florida has a population of 18,801,310
Illinois has a population of 12,830,632
Pennsylvania has a population of 12,702,379
Ohio has a population of 11,536,504
Michigan has a population of 9,883,640
Georgia has a population of 9,687,653
North Carolina has a population of 9,535,483
New Jersey has a population of 8,791,894
Virginia has a population of 8,001,024
Washington has a population of 6,724,540
Massachusetts has a population of 6,547,629
Indiana has a population of 6,483,802
Arizona has a population of 6,392,017
Tennessee has a population of 6,346,105
Missouri has a population of 5,988,927
Maryland has a population of 5,773,552
Wisconsin has a population of 5,686,986
Minnesota has a population of 5,303,925
Colorado has a population of 5,029,196
Alabama has a population of 4,779,736
South Carolina has a population of 4,625,364
Louisiana has a population of 4,533,372
Kentucky has a population of 4,339,367
Oregon has a population of 3,831,074
Oklahoma has a population of 3,751,351
Connecticut has a population of 3,574,097
Iowa has a population of 3,046,355
Mississippi has a population of 2,967,297
Arkansas has a population of 2,915,918
Kansas has a population of 2,853,118
Utah has a population of 2,763,885
Nevada has a population of 2,700,551
New Mexico has a population of 2,059,179
West Virginia has a population of 1,852,994
Nebraska has a population of 1,826,341
Idaho has a population of 1,567,582
Hawaii has a population of 1,360,301
Maine has a population of 1,328,361
New Hampshire has a population of 1,316,470
Rhode Island has a population of 1,052,567
Montana has a population of 989,415
Delaware has a population of 897,934
South Dakota has a population of 814,180
Alaska has a population of 710,231
North Dakota has a population of 672,591
Vermont has a population of 625,741
Washington, D. C. has a population of 601,723
Wyoming has a population of 563,626

Javascript: Using Canvas to cut an area of an image

Over the few weeks I’ve been working on a Canvas based side project (more on that soon) that involved cutting a mask out of a source image and placing it on a Canvas. In Photoshop parlance, this would be similar to creating a clipping mask and then using it to extract a path from the image into a new layer. So visually, we’re looking to achieve something similar to:

At face value, it looks like doing this with Canvas is pretty straightforward using the getImageData function. Unfortunately, if you look at the parameters that function accepts it’ll only support slicing out rectangular areas which isn’t what we’re looking to do. Luckily, if you look a bit further in the docs it turns out Canvas supports setting globalCompositeOperation which allows you to control how image data is drawn onto the canvas. The idea is to draw the mask on a canvas, turn on the “source-in” setting, and then draw on the image that you want to generate the slice off. The big thing to note here is that putImageData isn’t effected by the globalCompositeOperation setting so you have to use drawImage to draw the mask and image data.

So concretely how do you do this? Well check it out:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Lato:400,700,900' rel='stylesheet' type='text/css'>
    
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
        
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="underscore-min.js"></script>    
    <script src="fabric.min.js"></script>
    
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->    
  </head>
  <body>
  
  <canvas id="target" width="800px" height="400px" style="margin: auto"></canvas>
  
  <script>
  
  $(document).ready(function(){
      
      var mask = new Image(), bg = new Image();
      var mDf = $.Deferred(), bgDf = $.Deferred();
            
      mask.src = "grass_overlay.png";
      bg.src = "grass_texture.png";
      
      mask.addEventListener("load", function(){ mDf.resolve(this); });
      bg.addEventListener("load", function(){ bgDf.resolve(this); });
      
      var canvas = document.createElement("canvas"), ctx = canvas.getContext('2d');
      var target = document.getElementById("target"), targetCtx = target.getContext('2d');
      
      
      $.when(mDf, bgDf).done(function(){
          var l = (bg.width / 2) - (mask.width / 2), t = (bg.height / 2) - (mask.height / 2);
          
          canvas.width = bg.width;
          canvas.height = bg.height;
          
          ctx.drawImage(mask, l, t);
          ctx.globalCompositeOperation = "source-in";
          ctx.drawImage(bg, 0, 0);
                 
          var imageData = ctx.getImageData(l, t, mask.width, mask.height);                                       
          targetCtx.putImageData(imageData, 50, 50);                         
      });
      
  });
  
  </script>
  
  </body>
</html>

The code is running over at http://symf.setfive.com/canvas_puzzle/grass.html if you want to see it in action.

Anyway, happy canvasing!