Adapter Pattern in JavaScript

The adapter pattern is a concept where two incompatible interfaces are made to work together using the adapter. The adapter is useful for when changing frameworks in large complex projects. Say you started development using Backbone however after management makes an executive decision your team now has to align to the company’s standards which might be Dojo or Ember. This requires massive code change to switch all the Backbone code into Ember. This obviously is not a smart decision so using an adapter, while painful to do, is still better than the former option.

To implement an adapter interface we simply need to return a function or a set of functions that changes the current interface when consumed.

var AjaxLoggerAdapter = {
    log: function(arg) {
        AjaxLogger.sendLog(arg);
    }
};

/* Adjust the LoggerFactory */
var LoggerFactory = {
    getLogger: function() {
        // just gotta change what's returned here
        return AjaxLoggerAdapter;
    },
    ...
};

Source

Here the method for getLogger is overwritten to adapt the AjaxLoggerAdapter so that it uses the sendLog method of the object AjaxLogger. This allows us to externalize a function of an object to consume other implementations.

 
13
Kudos
 
13
Kudos

Now read this

Spirally Traversing a Two-Dimensional Array in JavaScript

This is a way to traverse a two-dimensional array (or a matrix) from the top left, spirally in a clockwise manner in JavaScript. This solution is inspired by functional programming and it uses tail recursion. Steps: When you start with... Continue →