Translate the JavaScript algorithm to Ruby.

This is a direct translation, and quite ugly.