Codility solution in JavaScript