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  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

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: