generalize javascript function