util.js

Summary

Shared utilities for the Mozile project.

Version: 0.8 $Id: overview-summary-util.js.html,v 1.15 2008/02/20 18:47:09 jameso Exp $

Author: James A. Overton


/* ***** BEGIN LICENSE BLOCK *****
 * Licensed under Version: MPL 1.1/GPL 2.0/LGPL 2.1
 * Full Terms at http://mozile.mozdev.org/0.8/LICENSE
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is James A. Overton's code (james@overton.ca).
 *
 * The Initial Developer of the Original Code is James A. Overton.
 * Portions created by the Initial Developer are Copyright (C) 2005-2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *	James A. Overton <james@overton.ca>
 *
 * ***** END LICENSE BLOCK ***** */

/**
 * @fileoverview Shared utilities for the Mozile project.
 * @link http://mozile.mozdev.org 
 * @author James A. Overton <james@overton.ca>
 * @version 0.8
 * $Id: overview-summary-util.js.html,v 1.15 2008/02/20 18:47:09 jameso Exp $
 */


mozile.provide("mozile.util.*");

/**
 * A collection of utility functions.
 * @type Object
 */
mozile.util = new Object();
// JSDoc hack
mozile.util.prototype = new mozile.Module;

/**
 * Output all an object's property and method names as a comma-separated string.
 * @param {Object} obj
 * @type String
 */
mozile.util.dumpKeys = function(obj) {
	var keys = new Array();
	for(var key in obj) keys.push(key);
	keys.sort();
	return keys.join(", ");
}

/**
 * Output all an object's keys and values as a newline separated string.
 * @param {Object} obj
 * @type String
 */
mozile.util.dumpValues = function(obj) {
	var result = new Array();
	for(var key in obj) {
		result.push( key +" = "+ obj[key] );
	}
	result.sort();
	return result.join("\n");
}

/**
 * Makes the first character of each word in the given string uppercase and returns the new string.
 * @param {String} string The string to capitalize.
 * @type String
 */
mozile.util.capitalize = function(string) {
	if(!string) return string;
	return string.replace(/\w+/g, function(a){
		return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
	});
}

/**
 * Pads a string with spaces.
 * Uses a crude caching technique.
 * @param {String} string The string to pad.
 * @param {Integer} length The desired length.
 * @param {Boolean} left Optional. When true the spaces are added to the beginning of the string.
 * @type String
 */
mozile.util.pad = function(string, length, left) {
	if(!string) string = " ";
	else string = String(string);

	if(!this._memory) this._memory = new Object();
	var id = string +":"+ length +":"+ left;
	if(this._memory[id]) return this._memory[id];

	var space = "";
	if(string.length < length) {
		for(var s=0; s < length - string.length; s++) space += " ";
	}

	var result;
	if(left) result = space + string;
	else     result = string + space;
	this._memory[id] = result;

	return result;
}

/**
 * Clone an object by making copies of all its properties.
 * @param obj The object to clone.
 * @param {Boolean} deep Optional. When true, the object's properties are cloned recursively.
 * @type Object
 */
mozile.util.clone = function(obj, deep) {
	var clone = new obj.constructor();
	for(var property in obj) {
		if(!deep)
		  clone[property] = obj[property];
		else if(typeof obj[property] == "object")
		  clone[property] = this.clone(obj[property], deep);
		else
		  clone[property] = obj[property];
	}
	return clone;
}


/**** JSON Methods ****/
/* These method are adapted from Douglas Crockford's json.js file:
 * http://www.json.org/json.js
 * The design has been changed to avoid prototyping, which should work better
 * with "for..in" loops in JavaScript.
 */

/**
 * Take a JSON string and return a JavaScript object.
 * @param obj The object to parse.
 * @type Object
 */
mozile.util.parseJSON = function(obj) {
    try {
        if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(obj)) {
            return eval('(' + obj + ')');
        }
    } catch (e) {
    }
    throw new SyntaxError("parseJSON");
}

/**
 * Take an object and return a JSON string.
 * @param obj The object to convert.
 * @type String
 */
mozile.util.json = function(obj) {
	switch(typeof(obj)) {
		case "boolean": return this.booleanToJSON(obj);
		case "number": return this.numberToJSON(obj);
		case "string": return this.stringToJSON(obj);
		case "object":
			switch(obj.constructor) {
				case Array: return this.arrayToJSON(obj);
				case Date: return this.dateToJSON(obj);
				default: return this.objectToJSON(obj);
			}
			break;
	}
	return "";
}

/**
 * Take an array and return a JSON string.
 * @param {Array} obj The object to convert.
 * @type String
 */
mozile.util.arrayToJSON = function(obj) {
    var a = ['['], b, i, l = obj.length, v;
    for (i = 0; i < l; i += 1) {
        v = obj[i];
        switch (typeof v) {
        case 'undefined':
        case 'function':
        case 'unknown':
            break;
        default:
            if (b) {
                a.push(',');
            }
            a.push(v === null ? "null" : this.json(v));
            b = true;
        }
    }
    a.push(']');
    return a.join('');
}

/**
 * Take a boolean and return a JSON string.
 * @param {Boolean} obj The object to convert.
 * @type String
 */
mozile.util.booleanToJSON = function(obj) {
	return String(obj);
}

/**
 * Take a date and return a JSON string.
 * @param {Date} obj The object to convert.
 * @type String
 */
mozile.util.dateToJSON = function(obj) {
    function f(n) {
        return n < 10 ? '0' + n : n;
    }

    return '"' + obj.getFullYear() + '-' +
            f(obj.getMonth() + 1) + '-' +
            f(obj.getDate()) + 'T' +
            f(obj.getHours()) + ':' +
            f(obj.getMinutes()) + ':' +
            f(obj.getSeconds()) + '"';
}

/**
 * Take a number and return a JSON string.
 * @param {Number} obj The object to convert.
 * @type String
 */
mozile.util.numberToJSON = function(obj) {
	return isFinite(obj) ? String(obj) : "null";
}

/**
 * Take an object and return a JSON string.
 * @param {Object} obj The object to convert.
 * @type String
 */
mozile.util.objectToJSON = function(obj) {
    var a = ['{'], b, i, v;
    for (i in obj) {
        if (obj.hasOwnProperty(i)) {
            v = obj[i];
            switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            default:
                if (b) {
                    a.push(',');
                }
                a.push(this.json(i), ':',
                        v === null ? "null" : this.json(v));
                b = true;
            }
        }
    }
    a.push('}');
    return a.join('');
}

/**
 * An associative array of string replacements.
 * @type Object
 */
mozile.util.m = {
	'\b': '\\b',
	'\t': '\\t',
	'\n': '\\n',
	'\f': '\\f',
	'\r': '\\r',
	'"' : '\\"',
	'\\': '\\\\'
};

/**
 * Take a string and return a JSON string.
 * @param {String} obj The object to convert.
 * @type String
 */
mozile.util.stringToJSON = function (obj) {
	if (/["\\\x00-\x1f]/.test(obj)) {
		return '"' + obj.replace(/([\x00-\x1f\\"])/g, function(a, b) {
			var c = mozile.util.m[b];
			if (c) {
				return c;
			}
			c = b.charCodeAt();
			return '\\u00' +
				Math.floor(c / 16).toString(16) +
				(c % 16).toString(16);
		}) + '"';
	}
	return '"' + obj + '"';
};









Documentation generated by JSDoc on Wed Feb 20 13:25:28 2008