refactor javascript code