Array::eachPair A useful method for interacting each element of an array with another (#32)

I’ve got this classic n2 collision detection code and I wanted to separate out all the iteration business into its own place. So I spent a long time trying to figure out the name for the method, searching around in case anyone had anything similar. I finally found it each_pair, which is exactly what I wanted. The each implies iteration, and we are iterating over each possible pair of items from the array.

###*
Call the given iterator once for each pair of objects in the array.

Ex. [1, 2, 3, 4].eachPair (a, b) ->
  # 1, 2
  # 1, 3
  # 1, 4
  # 2, 3
  # 2, 4
  # 3, 4

@name eachPair
@methodOf Array#
@param {Function} iterator Function to be called once for
each pair of elements in the array.
@param {Object} [context] Optional context parameter to be
used as `this` when calling the iterator function.
###
Array::eachPair = (iterator, context) ->
  length = this.length
  i = 0
  while i < length
    a = this[i]
    j = i + 1
    i += 1

    while j < length
      b = this[j]
      j += 1

      iterator.call context, a, b

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: