Javascript recursion and pattern matching with spread operator


Given an array of measurements ordered by time we have to implement a function that returns an array which will be filled with null measurements for every missing one.

In particular we want at least a measure for each hour after the time the first measure was taken.

This is necessary since we want to display this data in a chart which will try to connect this values with a line and we want to highlight missing measurements problems like in the following image.

Continue reading “Javascript recursion and pattern matching with spread operator”

A front-end tale: Google Places Library, jQuery promises and Coffeescript

When it comes to define my working position I often need to state (and clarify) the differences between design, frontend and backend development.
Given my academic background and my interests I can easily be considered more a backend developer than a frontend. I do not have a great “esthetic sense” and despite my knowledge of HTML5 and CSS (with all its SCSS, SASS, LESS and so on) I do not have the expertise of a “real frontend developer”.
Don’t get me wrong, I studied Javascript basics and I like to keep myself updated with its community news but still, it is not (at least for now ;P) my area of expertise.


Nevertheless I like to solve problems independently on their nature and so if there is a “frontend problem” to tackle I’m always ready to dive in.

This is exactly what happened last week.

Continue reading “A front-end tale: Google Places Library, jQuery promises and Coffeescript”

How to: Preview a resource in an iframe

Let’s say I have a form to create/edit a resource. On a side of this form I want to show a live preview of my resource. Whenever the form changes I need to update the preview.

At a first glance the solution seems pretty easy, right? Use an IFrame and update the src update on every change. Continue reading “How to: Preview a resource in an iframe”

A “desperate times call for desperate measures” hack

Last week I had to solve some tricky problems related to a Web application that needs to run locally on some tablets in kiosk mode without any Internet connection.

With the term kiosk mode I mean that the browser used to run the application, in this case Google Chrome, is wrapped in another application that is acting like a sandbox to prevent users from accessing the Operating System or any other application.

Continue reading “A “desperate times call for desperate measures” hack”

Opal under a microscope: Object creation in Ruby and JavaScript

In this post we’ll learn how Ruby objects are mapped in JavaScript-land by the Opal compiler, how to call methods on them and how object instantiation works for both Ruby and JavaScript.

The basics: constants, methods and instance variables

The rule by which Ruby objects are compiled into JavaScript by Opal is quite simple. Constants are registered with their regular name under the window.Opal (i.e. the Opal property on the JavaScript window object). Methods are mapped to properties prefixed by a $ (dollar sign). Instance variables are just regular properties.


The following Ruby code:

class Foo
  def initialize
    @bar = 'BAR!'

  def bar

  def baz

can be used from JavaScript in this way:

var Foo = Opal.Foo; // Constant lookup
obj = Foo.$new();   // calling method on class Foo             // accessing @bar      => 'BAR!
obj.$bar();         // another method call => 'BAR!'

obj.baz;            // a js property => undefined
obj.$baz();         // another method call => 'BAZ!'

As a Ruby developer you may be surprised that obj.baz returns undefined and not nil (actually window.Opal.nil) as that’s the value that you would expect to find while reading an instance variable for the first time.

What happens is that the Opal compiler will do just that, as long as you access those instance variables from Ruby code. In fact it statically analyzes the class’ code and pre-initializes to nil any instance variable for which it can find a reference.

Now that we have the basics let’s go further and put under the microscope for both Opal and CRuby.

The birth of an object in 3 steps

By looking in detail how object instantiation is done in JavaScript by the Opal compiled code we’ll have a chance to learn how it actually works in CRuby.

The implementation of .new

At the cost of oversimplifying here’s the rough implementation of the #new method available to all classes in Ruby:

class Class
  def new(*args, &block)
    obj = allocate # allocates the memory in CRuby
    obj.send(:initialize, *args, &block) # forwards all arguments to #initialize
    return obj

Breaking it down we see that:

  1. it calls #allocate in order to setup a raw object (in C it will also allocate the necessary memory)
  2. it forwards all arguments and block to #initialize
  3. it returns the object

Here’s how it looks in Opal (the code inside %x{} is JavaScript):

class Class
  def new(*args, &block)
      var obj = self.$allocate();
      obj.$initialize.$$p = block;
      obj.$initialize.apply(obj, args);
      return obj;

(Class#new source)

As you can see the the only notable difference is in how the block is passed. Opal will store any block call on the method itself under the $$p property. This way blocks can’t be confused with regular arguments. Apart from that it’s clear that it’s fundamentally the same code.

Uncovering Class#allocate

The curious reader at this point is wondering what the allocate method does in JavaScript because surely it can’t manage memory. Let’s see the implementation:

class Class
  def allocate
      var obj = new self.$$alloc;
      obj.$$id = Opal.uid();
      return obj;

(Class#allocate source)

Let’s break it down by line, but this time we’ll go in reverse order:

  1. The last line is the easiest one in which the code just returns the object: return obj.
  2. The middle one is still quite clear and seems to just assign a unique identifier to the object. That value will be the one returned by #object_id.
  3. The first and most important one is where stuff actually happens. The JavaScript new keyword is used to create an object whose constructor seem to be stored in $$alloc.

For those not very familiar with JavaScript I’ll show how objects are usually created:

// this function acts as the MyClass constructor
function MyClass() { = 'bar'; }

var obj = new MyClass;         // => 'bar'
obj.constructor // => MyClass

The awesome thing to me is that Opal manages to have an implementation that is really idiomatic in both Ruby and JavaScript.

3 Tricks to debug Opal code from your browser

1. Use pp

pp stands for Pretty Print and is part of the CRuby standard library. Usually what it does is just reformatting your output to make it readable.

require 'pp'
pp { 'hello' }

In CRuby would output:


Opal instead will just pass the object to console.log():

console.log output in Safari's console

2. Call Ruby methods from the browser console

Another good thing to keep in mind is how methods are mapped into JavaScript, the rule is really simple: $ is prefixed to the method name.

>$puts('hello world');
=> "hello world"

> Opal.Object.$new().$object_id();
=> 123

Once you know that, you can also learn how to call methods with and without blocks:

> Opal.send(, 'puts', 'hello world');
=> "hello world"

> var object = Opal.send(Object, 'new');
> Opal.send(object, 'object_id');
=> 123

> Opal.block_send([1,2,3], 'map', function(n) { return n*2 });
=> [2,4,6]

> Opal.block_send([1,2,3], 'map', function(n) { return Opal.send(n, '*', 2); });
=> [2,4,6]

3. Inspecting instance variables

Last but not least remember that instance variables are mapped to simple unprefixed properties of the JavaScript object.

Opal code:

class Person
  def initialize(name)
    @name = name

In the console (with JavaScript):

> var person = Opal.Person.$new('Pippo');
=> #<Person:123 @name="Pippo">

=> "Pippo"


That’s all for now, happy hacking!

Understanding throttling and debouncing of functions in JavaScript

Throttling and debouncing are arguably two concepts too often overlooked in front end development, even though they’re quite simple to grasp and bring major benefits when developing complex and/or intensive web applications.


Throttling and debouncing function calls basically prevent functions to be executed too many times in a specified time interval. More specifically:

  • Throttle will queue and execute functions calls at most once per given milliseconds
  • Debounce will execute the function once and filter all following calls until a given time has passed, then fire it again.

If you’re more a visual person, check out this interactive example to get how they work.

Ok, but when should I use them?

Throttling and debouncing are particularly useful when you need to listen (and react) to events that fire a lot of times, rapidly – think of a window resize, or a page scroll. If you try to attach a console.log() handler to one of those two events and fire them, you might have something like that:


That’s a lot of logs, right? Imagine if our handler function had to calculate different elements’ positions and had to move stuff around at the same time. Now, put this in the context of a heavy-interactive web application and your lag is served!

Enter throttle and debounce

That’s a perfect use case for some good ol’ throttling. 

The most famous implementation of the two is probably the Underscore.js one, which we’re going to use in our small example.

Its syntax is quite simple (from the Underscore.js docs): 

_.throttle(function, wait, [options])

Let’s put it in practice!

A _.throttle example

Our console.log() handler could be like this:

var i = 0;
var handler = function() {
  console.log('Scroll event fired ' + i + ' times!');

We’ll pass it as an argument to the _.throttle function, so that it will return our new, throttled handler: 

var throttledHandler = _.throttle(handler, 500);

Now, some jQuery sugar to listen for the scroll event and fire it:

$(window).on('scroll', throttledHandler);

Et voilà, less lag and a better approach to intensive Javascript application development:


You can see how our throttled handler function now fires at most once every 500ms.

If you’re interested in how throttling and debouncing work internally, take a look at the annotated source code provided by the Underscore.js pals!