John Zhang

Journal of Software Engineering

Read this first

How to Depreciate .success() and .error() in Angular 1.5

So Angular is depreciating .success() and .error() in $http. For anyone using the two methods, there’s two pieces of good news!

 1. Updating the calls is dead simple.

.then() takes a success function and an error function. You can just refactor your code from:

$http.get(...)
  .success(function(data, ...) {
    ...
  })
  .error(function(data, ...) {
    ...
  });

To:

$http.get(...).then(
  function success(response) {
    var data = response.data;
    ...
  },
  function error(response) {
    var data = response.data;
  });

 2. You can still use it (..for now)

If refactoring isn’t that simple for you, you’re still in luck! You can still enable .success() and .error() through $httpProvider. It defaults to true.. for now.

 Why The Depreciation?

.success() and .error() returns the original promise, as opposed to .then(), which returns a new promise. The two methods in question...

Continue reading →


Resolving Multiple Asynchronous Functions Just Once with Deferred Objects / Promises

I recently came across a piece of legacy code that had to pull data from multiple sources via AJAX requests, then combine it all. A simplified version looks like this:

var retrieveOne = function(source, cb) {
    $http.get(source).success(function(data){
        cb(data);
    });
};

var retrieveMany = function(sources, cb) {
    var dataArray = [];
    var _combine = function(data){
        if(data)
            dataArray.push(data);
        if(dataArray.length !== sources.length)
            return;
        //Continue combine...
        cb(dataArray);
    };
    for(var i = 0; i < sources.length; i++){
        retrieveOne(sources[i], _combine);
    }
};

retrieveMany([url1, url2, ...], processData);

It works, but it’s not great. We’re calling the private function _combine multiple times, when we really should be calling it once. The biggest drawback to this that comes to mind is that...

Continue reading →


How to Efficiently Merge Two Lists Unix Timestamps

Say you’re retrieving a comprehensive list of someone’s Github activities, and you now have data of each week’s additions, deletions, and commits. Great! We can just chart it out, nice and easy. Now, say someone comes in and asks to compare engineer A’s activities with engineer B’s activities.. on the same graph! Getting engineer B’s data is just calling Github’s API again, but organizing the data is the tricky part. We’ll have two sets of activities with two different sets of Unix timestamps, how do we resolve it?

If you google how to join two arrays in javascript, the top answers will tell you to concat the arrays then de-duplicate them after. The first Stack Overflow answer is O( n2 ).. that’s a lot of loops. Let’s see if we can get this time complexity down.

Since we are dealing with time here, we can exploit the fact that time progresses linearly and only run through our loop...

Continue reading →


How to Handle an OPTIONS Request in Express

So you need to enable CORS (cross-origin resource sharing) on your web application for whatever reason. Then you go to the top answer from Google:

var express = require('express');
var app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

We first add a middleware that’ll add the necessary headers to the response message, then move on and respond to GET and POST messages as usual. This works fine, but let’s see if we can improve on this. First off, we can add a line to terminate the response early instead of waiting the response to end in the method get or post:

...

Continue reading →


Bitwise Operations Part 3: The Logic Operators

Check here for Part 2, Binary and Two’s Complement.

In this post I’ll be covering all the logical bitwise operators in Javascript, but the principle is the same across all languages. There are so many cool and exciting things we can do with them, but that’ll be saved for later.

 What Do You Mean, Bitwise?

A bit is the smallest unit we can represent data in: ON/OFF, true/false, 0/1. If we string together 8 bits of data, we can call it a byte (though 1 byte doesn’t always mean 8 bits!). It’s practically unheard of nowadays to address units of memory in single bits, instead we use bytes for our needs. A byte is defined in C as an “addressable unit of data storage large enough to hold any member of the basic character set of the execution environment”. From hear on out, we will refer to a byte as 8 bits.

A byte can store up to 256 different values. Let’s take a look at an example byte...

Continue reading →


Bitwise Operators Part 2: Binary and Two’s Complement

Check here for Part 1, a quick introduction to numeric bases.

 Everything is a power of two

In this article, we’ll explore deeper into base 2, or binary, and prepare us for the groundworks of bitwise operations. Let’s start by counting to 10 in binary.

decimal binary decimal binary
1 0001 6 0110
2 0010 7 0111
3 0011 8 1000
4 0100 9 1001
5 0101 10 1010

In binary, each digit is no longer calculated in powers of ten. Instead, we have to think of each digit as a different power of two. Let’s see take a look at an example: 101 in decimal is 1*10^2 + 0*10^1 + 1*10^0. In binary, 101 is 1*2^2 + 0*2^1 + 1*2^0 = 5. It’s not important to be able to count in binary. As long as you understand the relationship between decimal and binary integers, we’ll be able to continue onward with bitwise operators.

 n-bit integers

When we say n-bit, what exactly do we mean by that? In...

Continue reading →


The ABC’s of Javascript: Apply, Bind, and Call

Let me start by saying that although grouping the three methods in the order above makes for a nice play on words, the functions should be better categorized as call and apply, then bind separately. And although the title is about these three functions, we’ll also learn how to manipulate the arguments object into an array, what happens when we set the context to null, and how to avoid scope problems with functions like setTimeout.

 The Call Function

The reason why we categorize the functions call and apply together is because they perform essentially the same thing: to invoke a given function with a target object as the context and optionally pass in arguments to the given function. Setting the function’s context is the same thing as setting the this variable inside of the function. Here is an example of call

var ann = {
  name: "Ann",
  greet: function{
    console.log("Hi, my name
...

Continue reading →


Evaluating the 8-Bit Hexadecimal RBG Color Model

Here’s a fun exercise: how does the computer know what color a 6 digit hex code should represent? In computing, you will often encounter values in base 16, or hexadecimal. In this base system, a single digit can represent values from 0 to 15. An immediate problem would be representing a value greater than 10 in a single digit. Here is where we enlist the alphabet to help us. 1010 is written as A16, 1110 as B16, 1210 as C16, 1310 as D16, 1410 as E16, and 1510 as F16. As the base increases, we enlist more help from the alphabet (and beyond). Read this post on numeric bases if you need a quick primer.

Now, let’s look at the 8-bit hex code color pallet. The RGB model can be represented as (x, y, z), where x, y, and z are integers from 0 to 255. Why 255? To answer that, let’s first think about what 8-bit means. One bit is the smallest unit of storage, on and off, which can be represented as...

Continue reading →


Bitwise Operations Part 1: A Quick Introduction to Bases

In this series, I will touch on the fundamentals of understanding binary and learning to reason with it, then how we can use it in Javascript.

 What is decimal notation, really?

We learn to count in decimals, or base 10. What this means is that each significant digits are counted in powers of 10. There is an infinite amount of base systems we can use, not just our familiar base 10. If we evaluate the same number in two different base systems, it would produce two completely different value. Let’s study the number 123. First in base 10, we would evaluate it like so:

12310 = 1*102 + 2*101 + 3*100 = 100 + 20 + 3

Now, let’s look at what 123 might look like in base 5.

1235 = 1*52 + 2*51 + 3*50 = 25 + 10 + 3 = 3810

So if we convert 123 from base 5 to base 10, it’s value would be 38. Instead of multiplying each digit in powers of 10, we evaluated it in powers of 5. Additionally, the...

Continue reading →


Javascript Floating Point (im)Precision and Solution

In an exercise to re-implement Javascript’s parseFloat(), I came across a common gotcha. Go ahead, try it yourself:

var pointThree = 0.1 + 0.2;
console.log(pointThree === 0.3); 

No, your console isn’t broken. 0.1 + 0.2 == 0.30000000000000004 according to IEEE 754. And yes, all the major implementations of adhere to this rule. Safari, Firefox, Internet Explorer, and even… Chrome….? Yes, even Chrome.
Why don’t they just fix it? At the hardware level, you can’t fix it because computers calculate in binary. This will understandably return rounding errors for most decimal numbers, due to the fact that most decimal numbers can’t be represented in finite binary numbers.

“It’s a feature, not a bug” -IEEE

Veteran programmers will recognize it as Floating Point Arithmetic. New programmers, unfortunately, will come to know this as the bug that wasted your last hour. Additionally, Javascript...

Continue reading →