Tag Archives: Javascript

Why Cat?

Sometimes, when new-comers come to functional programming, they see some things which may seem strange to them. Things which don’t make sense from an object-oriented perspective. I’m going to take an example of this and show you what I mean. Lets say we take the following Javascript function cat, which takes multiple arrays and merges them all into one (I am using the Ramda library to assist. Anything with the R prefix is a Ramda function):

var cat = function () {
  var head = R.head(arguments);
  if (head)
    return head.concat.apply(head, R.tail(arguments));
    return [];

The question may be posed, why bother with that function when Javascript has concat built in as a method on the Array prototype? The big difference is that concat is called on the object (the instance array), whereas cat operates on whatever is passed to it.:

// concat
[2, 1].concat([7, 6, 3, 4], [9, 6, 8]);
// returns [2, 1, 7, 6, 3, 4, 9, 6, 8]

// cat
cat([2, 1], [7, 6, 3, 4], [9, 6, 8])
// also returns [2, 1, 7, 6, 3, 4, 9, 6, 8]

It’s all about composability. Functional programming is a very “composable” paradigm. Functions (like cat) operate on whatever is passed to them as parameters. They do not operate on objects upon which they are methods. They are “free-standing” in nature. Lets see cat get composed as part of a bigger pipeline. Here, we have a function called splat. splat will basically flatten the arguments object of a function, similar to LINQ’s SelectMany:

var splat = function (fun) {
	return function(array) {
		return fun.apply(null, array);

Now, lets say we want to use cat to merge some arrays. But the arrays are buried in the item of a larger array. Here’s how we could solve that:

var flatCat = splat(cat);
var arraysToMerge = [[7, 6, 3, 4], [2, 1],[77, 2, 45]]; // the arrays are in the 1st and only index of this larger array
var result = flatCat(arraysToMerge);
// result will be [7, 6, 3, 4, 2, 1, 77, 2, 45];

This works nicely with cat, but you cannot pass Array.prototype.concat into splat. It just won’t work. It’s object-focused nature is its undoing. Run it yourself with concat, instead of cat, to see it bomb out and you’ll understand why it failed.

So, whilst our first glance at cat seemed to size it up as a pointless refactoring to achieve the same thing as Array.prototype.concat, I hope I’ve demonstrated that by tweaking the concept into a function which stands alone (separate from any “owning” object), we can use it as a composable part in a larger operation. Just one cog in the functional pipeline.

Just remember, cat operates on whatever is passed to it.

Dates in Javascript and UTC in the Browser

So dates are hard. Computer languages have varying success in implementing them. Take C#. If dates in C# were awesome, Jon Skeet would have had no cause to write Noda Time. I’m going to write a couple of posts about Javascript and dates, as they have caused me quite a bit of pain in recent months. Today, I will kick off with the UTC story (or lack thereof) for dates in Javascript (in the browser, anyway).

I’ll use C# to make a few comparisons in my analysis, just to highlight what is lacking.

As a really brief examination of what C# can do with dates in the context of UTC, just run the following:

var nowUTC = DateTime.UtcNow;
Console.WriteLine(nowUTC.ToLongDateString() + " " + nowUTC.ToLongTimeString() + " " + nowUTC.Kind);

You’ll see that you have a DateTime value which represents the UTC time for that point in time and has a Kind of UTC (not local). A DateTime can’t tell you what timezone it is in. It just knows whether it is local or UTC. Timezones (as distinct from offsets) are political and shift with policies of governments. So it is not trivial to build them into a computer language. Note: DateTimeOffsets are a generally better struct than DateTime and contain UTC and the offset from UTC. But the point is, here we have a UTC value representing a point in time and what that time is with a +0 UTC offset.

Now, lets turn our mind to Javascript. If you were to create a Date object, using the new keyword, and write that out to the console, it would look something like this:
Fri Jan 27 2017 22:04:36 GMT+1030 (Cen. Australia Daylight Time).

You can see there’s a time offset and even a helpful addition of the name of the timezone in brackets. Yay for Javascript. Now try and create a Javascript date object that is UTC (making sure you are located in a timezone other than the Zulu timezone, of course). Here’s a hint. You can’t. Not really, anyway.

But what about all those things you read on Stackoverflow, like toISOString and methods of the Date constructor such as getUTCFullYear etc.? Yes, lets talk about that.

First, I will dispense with toISOString. Some may say that to get UTC, you can just write:

var now = new Date();
var utcnow = now.toISOString();

The fact is, toISOString returns a string representation of UTC. Not a Date object. Now, you have a string. So my assertion holds.

What about a bit of sneaky epoch shifting? Say, we wrote something like this:

var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());

Have we achieved a UTC Date in Javascript yet? I would say no. If you log that Date object out to console, it would look a little like this:
Fri Jan 27 2017 11:34:36 GMT+1030 (Cen. Australia Daylight Time)
Look familiar? Sure, it’s 10.5 hours before the actual local time, but it still has the same local offset and timezone of the browser. So what happens if you now give that to a component which shifts the epoch again based on the offset? Now we are behind UTC. And we’ll have a Date object which still has the same offset. UTC has turned into a moving target, always leaping back in time by 10.5 hours.

But what about the static UTC method of the Date constructor? Something like:
var utc = Date.UTC(1900,08,18,0,0,0);
I hope you like milliseconds, because that is what that method returns. The number of milliseconds from Jan 1, 1970. And you can always pass that into a Date consructor, but you’ll just get a Date object with the browser offset and timezone.

And there’s one more scenario I’d like to cover. What if we call the Date constructor as a function? That is, without the new keyword?

var nowFromFunction = Date();

Sorry to disappoint, but that just returns a string. The string is local time as well. So, not a Date object and not UTC.

Now, it is true that Javascript dates track UTC internally. However, that is internals and components such as various HTML 5/Javascript datepickers don’t process internals.

Thus, unless someone can prove me wrong, I am asserting that you cannot create a UTC Date object in Javascript. Not like the way you can in C#.

Here’s a plunk to play with: Date plunk.

Oh and by the way, I was wondering why I did not pick this up when I learnt Javascript. So, I went back to the source – the Flanagan book. There is not a peep in there about how dates behave in the browser, vis-a-vis always stamping them with the local timezone and offset.

As I said at the outset, Dates are hard.

Currying to Rein in Underscorejs

Whilst I am a big fan of Underscorejs, today I am going to show you a small technique to rein it in. So, first I will show you the problem which I am going to solve.

When you use the Underscorejs methods for manipulating/iterating collections, Underscorejs usually passes in three parameters to the function which you use for the call-back:

  1. the current item being iterated;
  2. the index for that item in the collection; and
  3. the whole collection itself.

The easiest way to verify that, is to put a breakpoint in your function, open the console in either Firebug or Chrome developer tools and type the word arguments (see the following screenshot):


For one reason or another, you may want to confine the arguments which get passed in to the first one. You may be only interested in the item being iterated. And to lock your method down, you may want to effectively block the other 2 parameters from being passed in (note how I keep using the word “may”. Most of the time, you’ll be quite happy to have access to all 3 parameters).

To do that, I am going to write a small helper function which I will call curryOneArgument. That function will use the technique of currying to return a function that will only receive one argument:

var curryOneArg = function(fun) {
        return function(arg) {
            return fun(arg);

Now, all we have to do is wrap our call-back in that new function and we will be restricting that callback to only receive one argument from Underscorejs:

var newColl = _.map(coll, curryOneArg(function (arg) {
            return arg.name;

And, using the console to verify:



Underscore.js can Bind This!

underscore.js has a really neat method called bind that does something quite interesting. Let me first talk you through what that method is addressing.

One of the foibles in JavaScript is that the this pointer has a somewhat unusual behaviour in that it will point to the window object, when inside a nested function. Take the following example:

var car = {
	engine: 1,
	doorToWheelRatio: function (nrOfDoors){
		this.nrOfDoors = nrOfDoors;					
		return function (nrWheels) {
			//  'this' refers to window object in here
			return this.nrOfDoors / nrWheels;

There are two instances of this. The second one being in the nested function. That function is not going to behave as expected because the this pointer is pointing to the window object. This is a known foible, especially in light of the fact that the previous this pointer points at the car object.

The historical way in which developers have overcome that is to assign the this pointer to another variable in the enclosing function (e.g. self), thus making it available in the nested function:

var car = {
	engine: 1,
	doorToWheelRatio: function(nrOfDoors) {
		this.nrOfDoors = nrOfDoors;
		var self = this;
		return function(nrWheels) {
		  return self.nrOfDoors / nrWheels;

Using underscore.js’ bind function, we can effortlessly bind the this pointer in that nested function to the car object:

var car = {
	engine: 1,
	doorToWheelRatio: function (nrOfDoors){
		this.nrOfDoors = nrOfDoors;

		return _.bind(function (nrWheels) {
			return this.nrOfDoors / nrWheels;
		}, car);

Now both instances of this are pointing at the same object, car.

When I say effortlessly, bear in mind it comes at substantial cost. Take a look at this benchmark which I have performed at perf.com which clearly shows that using bind is an expensive operation compared with using a local variable (as was historically done).

It would be remiss of me not to point out that jQuery also has an equivalent function called proxy. That code would look like the following if we were to use proxy:

var car = {
	engine: 1,
	doorToWheelRatio: function (nrOfDoors){
		this.nrOfDoors = nrOfDoors;					
		return $.proxy(function (nrWheels) {
			return this.nrOfDoors / nrWheels;
		}, car);

That is all.

Underscore.js Avails Interesting Possibilities with Reduce

Since I began playing around with Underscore.js, I have become obsessed with its reduce method. reduce takes a collection (or an object) and returns a single value. But it is the way in which it does that which makes it compelling. From the documentation, its signature is:

_.reduce(list, iterator, memo, [context])

I’ll start out with a simple example. Probably the kind of example you’ll see everywhere around the Internet:

var result = _.reduce([100, 25, 2], function(memo, num) {
	 return memo / num;
// result === 2

The iterator function is being applied to each of the elements of the list. But not only that, it is making available to each iteration the result of the previous iterator-function’s result.

  • In the first iteration, memo has the value 100 and num is 25.
  • In the second iteration, memo has the value 4 and num is 2.

As you can see, the value of memo in the second iteration is equal to the result of the iterator function from the first iteration. So we have this concept of a value which is travelling through the iterations. The parameter memo is short for memoization. This is an implementation detail which is not relevant to this post. As that parameter travels from function to function through the iterations, I am using the name traveller for the purposes of this post.

There are only 2 iterations in this example because the list has 3 items and we have not passed it a seed value as the 3rd possible parameter. If we change that function to the following, we will get 3 iterations and the value of traveller on the 1st iteration will be 10000, whilst the value of num will be 100.

var result = _.reduce([100, 25, 2], function(traveller, num) {
	 return traveller / num;
}, 10000);
// result === 2

When it comes to the iterator function, you are free to be very creative in there. But first, I just want to point out that it is not limited to integers. The following example creates a sentence out of a string array:

var words = ['Reduce', 'is', 'an', 'interesting', 'method'];

var sentence = _.reduce(words, function(traveller, current) {
	var collate = traveller + ' ' + current;
	return collate;
//	sentence === 'Reduce is an interesting method'

You can also pass an object as the first parameter. This is where you can do some interesting stuff, like the following example that creates an address object from a person object:

var person = {
	name: 'Dave',
	age: 39,
	address: '28 Scenic Road',
	suburb: 'Kenmore',
	postcode: 4069

var address = _.reduce(person, function(traveller, objectValue, objectMember) {
    switch (objectMember) {
		case 'address':
		case 'suburb':
		case 'postcode':
			traveller[objectMember] = objectValue; break;
		default : break;
    return traveller;
}, {});

You can see that I have passed an empty object as the 3rd parameter to reduce, which will be the initial value of the traveller parameter.

Note that I’m not saying the last example is the best way to achieve that end. But that example does show that you can use the reduce function for a great many things beyond simple arithmetic and sentence construction.

Perhaps in a month or 2 I’ll have a really good example that solves a problem nice and elegantly.

Until then!