When to use ES6 proxies?

One of the most cool features of ES6 are proxies. Proxies are a special kind of objects to alter the semantics of other objects: access, deletion, setting, call semantics

As a meta-programming lover, I’m eager to use proxies for some fancy tricks. The other day I had the chance to use proxies and property getters while implementing an EventEmitter trait. I want to share the implementation to illustrate the differences between intercepting `get` semantics and using a `getter`.

Consider this:

function newEmitter() {
  var __handlers = new Symbol();
  return {
    on(type, handler) {
      this[__handlers][type].add(handler);
    },
    off(type, handler) {
      this[__handlers][type].delete(handler);
    },
    emit(type, ...args) {
      this[__handlers][type].forEach(handler => handler.call(this, ...args));
    },
    get [__handlers]() {
      var handlerSet = newHandlerSet();
      Object.defineProperty(this, __handlers, { value: handlerSet });
      return handlerSet;
    }
  };
}
function newHandlerSet() {
  return new Proxy(Object.create(null), {
    get(target, property) {
      if (!target[property]) { target[property] = new Set(); }
      return target[property];
    }
  });
}

Yep, the getter is gratuitous, it could be simply a computed property with the proxy but let do it this way for learning purposes.

Function `newEmitter()` creates an object ready to be mixed into an object prototype to use it as an event emitter. Methods `on()`, `off()` and `emit()` are trivially simple due to a couple of assumptions:

  1. The `__handlers` property will always be valid.
  2. Entries of the `__handlers` properties are always sets.

This allow us to avoid checkings on these properties and keep code simple.

Notice both functions, the getter and the get trap in the proxy give a solution for the same problems: to provide a default value for some properties. The difference is the nature of the knowledge we have about these properties. In case of the getter we want `__handlers` to default to a handler set so the getter overrides itself with an empty handler set. We specifically know which property we want to access in a special way and we implement the behaviour locally.

In case of the get trap we are altering not an specific property of an object but all the future properties. Actually, we are defining a new kind of object where all properties must be sets so we are changing the whole semantics of the object: as soon as we access a property, we obtain a set, if the property does not exist yet, we obtain an empty set. We implement this behaviour globally for all present and future properties.

You use getters to compute properties. While you use get traps to alter semantics. Do you know how to calculate an specific attribute? Use a getter for that attribute. Do you want to change the fact of accessing properties, in general, use the get trap.

Oh! And please, do not use proxies for controlling access or extending or restricting APIs, you already have inheritance and composition for that!

Proxies are really powerfull. I hope to show you more usages soon.

Static vs. Dynamic Typing

The other day I was invited to participate in the podcast of Nación Lumpen about the flaming topic Dynamic Typing vs. Static Typing. Luis Osa and I were there to argue in favor of dynamic typing, from Python and JavaScript perspectives respectively.

My first impression after the podcast was that we were not at the level to defend dynamic languages properly and I ended very surprised about the modern features of static typed languages.

Lots of things were told during the conversation and, in my opinion, lots of reasons arose to make static typed languages shine over dynamic ones. After 700 km of highway, I’ve got to sort my ideas and conclusions about the podcast. This is a long post, so be prepared!

Types are meaning

From the bare metal perspective, types are nothing. The pure hardware executing the programs in our devices understand only about memory addresses and data sizes. It does not perform any type-checking before running the assembly code, once the code it’s loaded, it’s on its own.

You start introducing types to mean something. Consider simple types in C: they are all about data sizes (int, word, byte), formats (float, double, pointer) and access (const) but you’re helping the compiler to create better target code: memory efficient, faster and safer. In addition, C gives us ways to combine simpler types into complex ones as well by using DEFINE macros and structured types. C is able to calculate each size, format and access type of the new abstraction preventing us from accessing invalid fields of a record or using them in incorrect places but, in addition, C makes new names to be charged with unique meaning (i.e two structures differing only in the name of the structure are actually different types) so we can abuse this feature to create abstract relationships.

This is what I think when talking about types. Types are (or at least, add) meaning. You use types as a way to perform a classification of data, to label some properties that some set of values should have and to establish relationships with other types.

Seguir leyendo “Static vs. Dynamic Typing”

Offliner: switch the Web offline

Offliner is a proof of concept about bringing offline web applications through service workers.

Service workers allows the developer to intercept resource requests to the network and take control of the fetching process. In addition with caches, service workers enable the Web to success where AppCache failed.

Offliner is a project aimed to provide a service worker intended to be as transparent and automatic as possible while keeping a lot of customization power. It tries to always fetch from network and fallbacks to cache when remote resources are unreachable for any reason. You can follow Offiliner on GitHub.

Charlas de presentación del máster Telefónica en desarrollo avanzado

Como lo prometido es deuda, por fín han anunciado los horarios y la programación de las charlas de promoción del máster que podéis encontrar resumidas a continuación y en detalle en el enlace anterior:

Todas las charlas son en el edificio Oeste 1, sala F11 a las 09:30h. Mi recomendación es que lleguéis con tiempo para gestionar el permiso de entrada.

¡Nos vemos allí!

ya! library for go routines in JavaScript (Next, ES6)

ya! is a go-routine implementation in ES6 using generators and promises, inspired by task.js

A month ago I discovered Go language, a kind of modern C designed by Robert Griesemer, Rob Pike, and Ken Thompson inside Google and after passing the online tutorial I ended fascinated by go-routines and channeled communications.

In Go language a go-routine is any function launched by using the go keyword.  Unlike co-routines, a go-routine has no explicit control over its execution and it is a runtime scheduler who is in charge of pausing and resuming routines. A go-routine is a green thread ruled by the go runtime.

In Go, communications between go-routines are made explicit by using channels (the communication model is based on Communicating Sequential Processes). A channel can receive or send data. When a go-routine is sending data to a channel but nobody is waiting for that data in the same channel, the go-routine blocks until someone consumes the data. The same happens when getting data and there is no data available.

Generators in JavaScript in addition to a simple scheduler enable this kind of collaboration and ya! is a library to emulate Go go-routines related features such as go-routines themselves, channels (buffered and unbuffered) and special Go statements like select (range is coming!).

You can find the library in bower under the name of ya.js and read the docs or see the annotated source on GitHub.

As an extra, here you have the go version of the dinning philosopher problem and the JS version using ya!

Seguir leyendo “ya! library for go routines in JavaScript (Next, ES6)”

Master Telefónica en desarrollo de software avanzado en la U-TAD

Los que sigáis este blog sabéis de sobra que soy desarrollador de Firefox OS en Telefonica I+D y profesor de JavaScript en mis ratos libres. Empezando este Octubre también impartiré, junto a compañeros de profesión, parte del Máster en desarrollo de Software Avanzado en la U-TAD.

Podéis leer la información oficial del máster en la página de la U-TAD y la no oficial, a continuación…

Seguir leyendo “Master Telefónica en desarrollo de software avanzado en la U-TAD”

LaTeX Keyboard in the Firefox OS Marketplace!

Google Summer of Code 2014 is about to end and next Monday is the official pencils-down date in which our students should stop producing code. Fortunately, I’m proud to announce my mentee, Raniere Da Silva, has released his LaTeX Keyboard for Math in the Firefox OS Marketplace. Notice you need Firefox OS 2.0 or greater to use it.

The keyboard includes:

  • Five layouts for a default English input, numbers and symbols, greek letters (with uppercase variations), functions and operators.
  • The common forms of functions and operators contain alternatives for less common variations of themselves.
  • An input assistant to automatically enter and leaving LaTeX math contexts.
  • Placeholder navigation between LaTeX math commands.

Seguir leyendo “LaTeX Keyboard in the Firefox OS Marketplace!”

Math keyboard for Firefox OS

I did not mention it before but I’m mentoring a project for Mozilla in the Google Summer of Code of this year. My mentee is Raniere Silva, a math student from Brazil. He is working on a mathematical keyboard and he just released a demo today. There is already work to be done, of course but the project is working well. Check the demo following his tutorial about how to install the new Math layouts on a Firefox OS device (Flatfish tablet included!)

Greek letters layout
Common math functions

Introducing strongforce: an infrastructure for game engines

The strongforce library is a light-weight framework to build game engines. It provides a backbone for a powerful game loop and helper classes for efficiently implement new game components such as models, renders and simulators. Main framework features include:

  •  Model oriented.
  •  Decoupled simulation and render loops.
  •  Real time simulation loop for integration with physics engines.
  •  Separated read and write stages during simulation to avoid expensive model copies.
  •  Versatile and dynamic visitor pattern to implement the Game Model Hierarchy.
  •  Use of JavaScript functors to quickly implement simple renders or simulators.
  •  Helper classes to ease implementation of Renders and Simulators.
  •  Events for Model to allow asynchronous programming.
  •  Fully control of the loop step and execution.
  •  Careful separation of responsibilities allowing the developer to focus on data model, business logic and rendering process separately.

Strongforce is not a graphic engine, not even a game engine. It is only a proposal for a game architecture and a main loop. You can read more about the framework internals and philosophy of design in the wiki pages of the repository or further in this post. Please feel free to provide any feedback by opening new issues on GitHub.

Seguir leyendo “Introducing strongforce: an infrastructure for game engines”