Monthly Archives: February 2014

Simple Registry Pattern Implementation in JavaScript

Have you ever had to deal with something like this?

switch (input) {
    case '200':
        correspondingEvent = 'success';
    case '404':
        correspondingEvent = 'error';
    case '500':
        correspondingEvent = 'error';
    // etc...

A huge switch statement that you cannot dynamically change. There is a design pattern called Registry Pattern for exactly this case. It is basically an object/array which maps different conditions.

Here is a JavaScript implementation of said pattern:

var registry = {
    '200': 'success',
    '404': 'error',
    '500': 'error',
    '403': 'error',

var input = '200', correspondingEvent;

if (input in registry) {
    correspondingEvent = registry[input];   
} else {
    // handle invalid input   

Adding or removing new cases is very easy:

registry['401'] = 'error';
delete registry['401'];

I would like to thank Christian Strotz for opening my eyes on this one, since I originally used an array instead of an object. (like in most other programming languages).

My Sublime Text 2 Configuration

Here is my Sublime Text 2 configuration file. Install these packages before applying it:

  • Github Color Theme
  • Theme – Centurion
  "bold_folder_labels": true,
  "color_scheme": "Packages/Github Color Theme/GitHub.tmTheme",
  "drag_text": false,
  "folder_exclude_patterns": [
  "font_size": 10,
  "highlight_line": true,
  "line_padding_bottom": 2,
  "line_padding_top": 2,  
  "show_tab_close_buttons": false,
  "tab_size": 2,
  "theme": "Centurion.sublime-theme",
  "translate_tabs_to_spaces": true,
  "use_tab_stops": true,
  "word_wrap": true

Screenshot of the editor (looks very similar on OS X)

dark theme