fold right and then left in javascript