Perl code rewritten as Javascript from Higher-Order Perl