refactor javascript to make it more general-purpose and reusable