Solution 2 in JavaScript