Posts Tagged javascript

Select distinct for MongoDB

Here is a handy script I’ve been using for MongoDB to retrieve a list of all the fields used in a collection. This uses a map/reduce routine and has to comb over all the documents in a collection so you may want to exercise caution when using this script.

// usage:
// mongo localhost/foo --quiet --eval="var collection='bar';" getcollectionkeys.js
var mr = db.runCommand({
  "mapreduce":collection,
  "map":function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce":function(key, stuff) { return null; }, 
  "out":collection + "_keys"
})

print(db[mr.result].distinct("_id"))

db[collection+"_keys"].drop()
Share/Save

Tags: , , ,

node.js at Facebook

Slides

Tags: , , ,

Ext.ux.JSONP for ExtJS 4

Here is a solution for making simple JSONP requests in ExtJS 4

Ext.define('Ext.ux.JSONP', {
    extend: 'Ext.data.ScriptTagProxy',
    alias: 'ux.jsonp',

    createRequestCallback: function(request, operation, callback, scope) {
        var me = this;
        
        return function(response) {
            callback.apply(scope, [response]);
            
            operation.setCompleted();
            operation.setSuccessful();
            me.afterRequest(request, true);
        };
    }
});

Tags: , , , ,

Simple message bus for extjs 4

Here’s a simple message bus/broker I wrote for Ext.js 4

Ext.define('Ext.ux.MessageBroker', {
    extend: 'Ext.util.Observable',

    statics: {
        instance: null,
        setInstance: function(i) {
            this.instance = i;
        },
        sendMessage: function(msg, data) {
            this.fireEvent('message',{"msg":msg,"data":data});
        }
    },

    constructor: function(config){
        this.addEvents({
            "message" : true
        });

        if(config && config.listeners) this.listeners = config.listeners;

        Ext.ux.MessageBroker.superclass.constructor.call(this, config)
    }

}, function() {
    Ext.ux.MessageBroker.setInstance(new Ext.ux.MessageBroker());
});


// Sending a message:
Ext.ux.MessageBroker.sendMessage("load_stock", {"symbol":"INTC"});

// Recieving a message:
Ext.util.Observable.observe(Ext.ux.MessageBroker);
Ext.ux.MessageBroker.on('message', function(msg) {
    console.log('message fired: ',msg);
});

Tags: , ,

Calculate a color gradient in Javascript

Here is a simple Javascript class to calculate the percent of a gradient between two colors given the percent (as a float 0-1) and two colors. Uses functions from php.js.

Color = function() {
};

Color.hexdec = function(hex_string) {
    hex_string = (hex_string + '').replace(/[^a-f0-9]/gi, '');
    return parseInt(hex_string, 16);
}

Color.dechex = function(number) {
    if (number < 0) {
        number = 0xFFFFFFFF + number + 1;
    }
    return parseInt(number, 10).toString(16);
}

Color.pad = function(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

Color.calcgrad = function(val, color1, color2) {
    
    if(!color1.match(/^#[0-9a-f]{6}/) || !color2.match(/^#[0-9a-f]{6}/)) return 'match err!';
    
    if (val > 1) {
        val = 1;
    }
    if (val < 0) {
        val = 0;
    }
    val = parseFloat(val);
    
    c1 = [Color.hexdec(color1.substr(1,2)), Color.hexdec(color1.substr(3,2)), Color.hexdec(color1.substr(5,2))];
    c2 = [Color.hexdec(color2.substr(1,2)), Color.hexdec(color2.substr(3,2)), Color.hexdec(color2.substr(5,2))];
    
    if (val < .5) {
        delta = [(c2[0] - c1[0]), (c2[1] - c1[1]), (c1[2] - c2[2])];
        arrColor = [c1[0] +1 * 2), c1[1] -2 * 2), c1[2] -3 * 2)];
    }
    return '#'+Color.pad(Color.dechex(arrColor[0]),2)+Color.pad(Color.dechex(arrColor[1]),2)+Color.pad(Color.dechex(arrColor[2]),2);
}
  1. delta[0] * val) * 2), c1[1] + ((delta[1] * val) * 2), c1[2] - ((delta[2] * val) * 2)]; } else { delta = [(c1[0] - c2[0]), (c1[1] - c2[1]), (c1[2] - c2[2])]; arrColor = [c1[0] - ((delta[0] * (val - .5 []
  2. delta[1] * (val - .5 []
  3. delta[2] * (val - .5 []

Tags: , , ,

Javascript implementation of Java’s String.hashCode() method

Here is a direct replacement for Java’s String.hashCode() method implemented in Javascript.

I wrote this function to fulfill a requirement at work. Apparently, the back-end engineers thought hashCode() was a standard function. One of the hurdles for this project was not only figuring out how to translate the mathematical formula used in Java to generate hashCode()’s but also how to force Javascript to use 32bit integer math (no small feat).

Fortunately, I discovered that Java supports bitwise operators which are constrained to 32bit integer math.

So here’s the resulting String prototype in Javascript. With this prototype you can simply call .hashCode() on any string, ie. “some string”.hashCode(), and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.

String.prototype.hashCode = function(){
	var hash = 0;
	if (this.length == 0) return hash;
	for (i = 0; i < this.length; i++) {
		char = this.charCodeAt(i);
		hash = ((hash<<5)-hash)+char;
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
}

Tags: , ,

Primitive OOP observer pattern with ExtJS

Recently I embarked on a quest to design a framework which would help us keep track of large and complex javascript projects in easily identifiable and extendable patterns. After some thought and deliberation, we eventually settled on the observer pattern using Ext’s Ext.util.Observable object as the base object to use in responding to event broadcasts and the Ext.ux.BroadcastEvents plugin for managing global event broadcasts.

Here is the code I came up with for common component elements:

ComponentWrapperBase = Ext.extend(Ext.util.Observable, {
	delayBuild: false,
	
	eventObj: {
			"buildwidget": true,
			"showwidget": true,
			"destroy": true,
			"refresh": true
		},
		
	globalEvents: [],
	
	widget: null,
	widgetCfg: null,
	
	build: function() {
		if (this.widgetCfg && !this.widget) {
			//console.log("buildwidget", this);
			this.widget = Ext.ComponentMgr.create(this.widgetCfg);
			this.widget.wrapper = this;
			this.fireBuildEvent();
		}
	},
	
	fireBuildEvent: function() {
		this.fireEvent("buildwidget", this, this.widget);
	},
	
	showWidget: function(locationId) {
		if (this.widget) {
			if (this.widget.xtype == "window") {
					if (locationId != null) {
						this.widget.show(locationId);
					} else {
						this.widget.show();
					}
			}
			else {
			
				if (locationId != null) {
					this.widget.render(locationId);
				}
				else {
					this.widget.render();
				}
			}
			this.fireEvent("showwidget", this);
		}
	},
	
	constructor: function(config){
		if (config) {
			if (config.widgetCfg) {
				this.widgetCfg = config.widgetCfg;
			}
			
			if (config.delayBuild) {
				this.delayBuild = config.delayBuild;
			}
			
			// Copy configured listeners into *this* object so that the base class's
			// constructor will add them.
			if (config.listeners) {
				Ext.apply(this.listeners,config.listeners);
			}
			
			if(config.events && Ext.isArray(config.events)) {
				for (var i=0; i

This creates a simple widget wrapped in an Observable object. You can reach the contained widget through wrapper.widget. Using the framework above, here's how you could create a simple widget.

SimpleTextField = Ext.extend(ComponentWrapperBase, {
	widgetCfg: {
		xtype: 'textfield',
		fieldLabel: 'Name'
	},
	constructor: function(config){		// Constructor is not required, but I've included 
							// it to demonstrate the flexibility of this framework
		if (config) {
			Ext.apply(this,config);
		}
		
		this.widgetCfg.value = 'John Smith';
		
		SimpleTextField.superclass.constructor.call(this);
	}
});

var simpleTextField = new SimpleTextField();
// Actual component is available at simpleTextField.widget, useful for adding to other containers

That's it! If you have any questions or comments, feel free to post them below.

Tags: , , , , ,

Cleaning up unresponsive script errors

I recently worked on improving performance in a labor scheduling application. The app was originally designed to load all the employees at one time in one large chunk, processing and stuffing the data into various places as needed on startup. This all worked fairly well on average stores with 50-100 employee records until we discovered several stores with 100+ employee records which caused the browser to display an unresponsive script warning due to the rather heavy pre-processing algorithms.

After scouring the web for clues to help me get rid of this warning without changing settings on the browser, I found out that the only way to avoid these warnings was through a pseudo-threading pattern using setTimeout12.

One of the patterns I came up with to process a sequence of commands (such as adding records to a store) one at a time while still allowing the browser time to refresh and process other commands:

var chainedTasks = [
   function() {
      console.log('first set of tasks');
   },
   function() {
      console.log('second set of tasks');
   },
   function() {
      console.log('third set of tasks');
   }
];

var currentTaskNum = 0;
var isExecuting = false;
var emptask = {var emptask = {
	scope: this,
	interval: 100,
	run: function(){
		if(currentTaskNum > chainedTasks.length) {
			Ext.TaskMgr.stop(emptask);
		}

		if (!threadIsRunning) {
			threadIsRunning = true;
			if (typeof chainedTasks[currentTaskNum] === 'function') {
				chainedTasks[currentTaskNum](currentTaskNum);
			}
			currentTaskNum++;
			threadIsRunning = false;
		}
	}
};
Ext.TaskMgr.start(emptask);
  1. http://www.dojotoolkit.org/forum/support/general-support/need-suggestions-how-manage-firefox-warning-unresponsive-script []
  2. http://dev.opera.com/articles/view/efficient-javascript/?page=all []

Tags: , , , ,

Javascript resources

Being a scripted language whose behavior can vary depending on the browser environment it is run in, Javascript can be particularly difficult to work with and debug sometimes. Here are a few tools I’ve found to be helpful:

These are the most helpful Javascript tools I’ve found. If you know of any more feel free to mention them in the comments below. Happy coding!

Tags: , , ,

Warning: JSLint will hurt your feelings

JSLint is a very helpful code quality utility for javascript that purports to hurt your feelings but helps you write ECMAScript compliant code. Many development suites like Aptana now include lint checking while you code.

A major advantage of making sure your code is linted is that it ensures your code will not be mangled too badly by minification/obfuscators if you decide to use them later on.

Tags: , , , , , , ,