Javascript refactor