JavaScript refactoring: make functions out of redundant code