Functional JavaScript solution.