JavaScript #4; improved algorithm for Perl #4.