refactor js to utilize recursion