Developing Feather-Weight Webservices with JavaScript

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

« Extending the native String() class · Extending the native Number() class »
Google
 
Web Developing Featherweight Web Services with JavaScript
This is version 0.57b of this manual. It is a beta version with some gaps. We are grateful for feedback.

The code is the manual has not yet been fully tested against Internet Explorer. Bug reports are welcome.
An Elektrum Press Online