Array#extremes Useful JavaScript Game Extension #30

###*
 * Returns an object containing the extremes of this array.
 * 
 * @param {Function} [fn] An optional funtion used to evaluate 
 * each element to calculate its value for determining extremes.
 * @returns {min: minElement, max: maxElement}
 * @type Object
### 
Array::extremes = (fn) ->
  fn ||= (n) -> n
 
  min = max = undefined
  minResult = maxResult = undefined
 
  this.each (object) ->
    result = fn(object)
 
    if min?
      if result < minResult
        min = object
        minResult = result
    else
      min = object
      minResult = result
 
    if max?
      if result > maxResult
        max = object
        maxResult = result
    else
      max = object
      maxResult = result
 
  min: min
  max: max

Usage:

[-1, 3, 0].extremes() # => {min: -1, max: 3}

test "#extremes", ->
  array = [-7, 1, 11, 94]
 
  extremes = array.extremes()
 
  equals extremes.min, -7, "Min is -7"
  equals extremes.max, 94, "Max is 94"
 
  extremes = array.extremes (value) ->
    value.mod 11
 
  equals extremes.min, 11
  equals extremes.max, 94

Array#wrap Useful JavaScript Game Extension #29

/**
 * Pretend the array is a circle and grab a new array containing length elements. 
 * If length is not given return the element at start, again assuming the array 
 * is a circle.
 *
 * @param {Number} start The index to start wrapping at, or the index of the 
 * sole element to return if no length is given.
 * @param {Number} [length] Optional length determines how long result 
 * array should be.
 * @returns The element at start mod array.length, or an array of length elements, 
 * starting from start and wrapping.
 * @type Object or Array
 */
Array.prototype.wrap = function(start, length) {
  if(length != null) {
    var end = start + length;
    var result = [];
 
    for(var i = start; i < end; i++) {
      result.push(this[i.mod(this.length)]);
    }
 
    return result;
  } else {
    return this[start.mod(this.length)];
  }
};

Simple use:

[1, 2, 3].wrap(-1) => 3

[1, 2, 3].wrap(6) => 1

Or get fancy and tile your kitchen:

["w", "o", "o", "o"].wrap(0, 16) => ["w", "o", "o", "o", "w", "o", "o", "o", "w", "o", "o", "o", "w", "o", "o", "o"]

Array#clear Useful JavaScript Game Extension #28

Here’s a useful little method that empties out an array. Sure you could type myArray.length = 0; but that is kind of weird. For some reason myArray.clear() just makes more sense to me.

/**
* Empties the array of it's contents. It is modified in place.
*
* @type Array
* @returns this, now emptied.
*/
Array.prototype.clear = function() {
  this.length = 0;
  return this;
};

The series continues…