Thursday, February 21, 2013 Thursday, February 17, 2011

Custom Array-like objects

function Collection() {
	var i = 0, len = arguments.length;
	if (len == 1 && typeof arguments[0] == 'number') {
		for (i; i < arguments[0]; ++i) {
			this[i];
		}
	} else {
		for (i; i < len; ++i) {
			this[i] = arguments[i];
		}
	}
	
	this.length = i;
}

Collection.prototype = new Array();
Collection.prototype.constructor = Collection;
Collection.prototype.toString = function () {return this.join()};

var arr = new Array(6);
var dc = new Collection(6);

arr.push('test');
dc.push('test');

console.debug(arr, 'Array');
console.debug(dc, 'Collection');

So far this is working in Chrome 9, Safari 5 and Firefox 3.6. I’ll update this as I test each new browser, biut it’s safe to say it wont work in IE6

Monday, January 17, 2011

Character Arrays

/*
Character Arrays

whilst this is a useless example
it demonstrates the use of a string
as a character array
*/

var foo = "this is a string";


for (var i = 0, len = foo.length; i < len; ++i)
    console.log(foo[i]);


/*
Result:
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g
*/
Sunday, January 16, 2011

Short hand timestamp

/*
Short hand timestamp

As far as I know, this is
the quickest shortest method 
to get the current timestamp
*/
+new Date;

Friday, January 14, 2011

Shortest conditional statement

/*
Short hand conditional

This is similar to Optional constructor arguments
utilising right hand evaluation if left hand results 
in boolean true
*/

var foo = 2, bar;
foo == 2 && (bar = 3);


/*
Can also be used to call functions conditonally
*/
foo == 2 && baz();
Thursday, January 13, 2011

Object properties to Array

/*
Collecting object properties into
an Array
*/

var i = 0, arr = [];
var foo = {bar: "value bar", baz: "value baz"};

for(arr[i++] in foo)


/* 
Result:
arr == ["bar", "baz"] 
*/
Monday, January 10, 2011

Optional constructor arguments

/*
Setting object parameters 
optionally in the constructor

bar is required, baz is optional


Note:
false or 0 will result in no value being 
used. Better to use conditions in this case.
*/

function foo(bar, baz) {
    this.bar = bar;
    baz && (this.baz = baz);
}

foo.prototype = {
    bar: "",
    baz: ""
};

Function arguments with defaults

/*
Function with defaulted arguments
bar is required, baz is optional with a default


Note:
false or 0 will result in the default value being 
used. Better to use conditions in this case.
*/
function foo(bar, baz) {
    baz = baz || 'default value';
}