javascript algorithm