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

Leave a Reply

Your email address will not be published. Required fields are marked *