Inmatarian's solution in Javascript