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
