Extending the native Array() class
You can see parts of this class in use in Configurable greeking and Using JS code libraries, part 2.
/* Code from "Developing Featherweight Web Services with JavaScript" http://feather.elektrum.org/ (c)An Elektrum Press, retain this notice License: http://feather.elektrum.org/appendix/licenses.html */ Array.prototype.serial = function () { switch( this.length ) { case 0 : return false; case 1 : return this[0].toString(); case 2 : return this.join(' and '); default: return this.slice(0,-1).join(', ') + ', and ' + this[ this.length - 1 ]; } } Array.prototype.sum = function () { var sum = 0; for ( var i = 0; i < this.length; i++ ) sum += this[i]; return sum; } Array.prototype.isIn = function ( what ) { if ( ! what ) return false; for ( var i = 0; i < this.length; i++ ) { if ( this[i] == what ) return true; } return false; } Array.prototype.dedup = function () { var newArray = new Array (); var seen = new Object (); for ( var i = 0; i < this.length; i++ ) { if ( seen[ this[i] ] ) continue; newArray.push( this[i] ); seen[ this[i] ] = 1; } return newArray; } Array.prototype.max = function () { var max = new Number(); for ( var i = 0; i < this.length; i++ ) { if ( this[i] > max ) max = this[i]; } return max; } Array.prototype.min = function () { var min = new Number(); for ( var i = 0; i < this.length; i++ ) { if ( this[i] < min ) min = this[i]; } return min; } Array.prototype.mean = function () { return this.sum() / this.length; }
Live tests
All original content is ©2004-2005 an elektrum press, all
rights reserved. For code use, please see Licenses and terms of use.