javascript: remove duplicated code