Convenience Functions

Array.append

Append each element of source to this array. This is similar to Array.concat except it modifies this array rather than returning a new array.

Array.prototype.append = function(source) {
    if ( source instanceof Array ) {
        for ( var i = 0; i < source.length; ++i ) {
            this.push(source[i]);
        }
    }
    else {
        this.push(source);
    }
}

Array.contains

It is often necessary to determine if an array contains an specific object. The Array class is easily extended with a contains method that returns true if this array contains a specified object.

Array.prototype.contains = function(object) {
    var result = false;
    for ( var i = 0; i < this.length; ++i ) {
        if ( this[i] === object ) {
            result = true;
            break;
        }
    }
    return result;
}

String.format

The format method formats a message string by replacing positional parameters in this string. When it encounters a positional parameter "{n}" in the this string, it replaces it with the Nth element of the parameter list. If a string contains a positional parameter {i} and the argument list contains less than i arguments, the positional parameter is not replaced.

String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g, function() {
	var arg = args[arguments[1]];
        return arg ? arg : arguments[0];
    });
};
Example:
var s = "{1} + {2} = {3}";
s.format('one', 'two', 'three');  // returns "one + two = three"
s.format('two', 'four');          // returns "two + four = {3}"

implements

implements is used in debugging and to demonstrate that the object named by s1 implements the interface named in s2.

/**
 * Output a message on the console indicating if the object named
 * in string s1 implements the interface named in string s2.
 * @param s1  the name of an object in the current scope.
 * @param s2  the name of a class in the current scope.
 */
function isInstance(s1, s2) {
    var cls = this[s2];
    console.log(s1 + " is" + (this[s1] instanceof cls ? "" : " not") +
                " an instancce of " + s2);
}

isInstance

isInstance is used in debugging and to demonstrate the isA relationship of an object and its class or base classes.

/**
 * Output a message on the console indicating if the object named
 * in string s1 is an instance of the class named in s2.
 * @param s1  the name of an object in the current scope.
 * @param s2  the name of a class in the current scope.
 */
function isInstance(s1, s2) {
    var cls = this[s2];
    console.log(s1 + " is" + (this[s1] instanceof cls ? "" : " not") +
                " an instancce of " + s2);
}