Codility Solution-Javascript