I've challenged myself to come up with another JS solution. Highly functional, with sorting of the output but without the sort function. Here it comes, including test cases:
const solution = x => x.reduce( (r, vfirst) => [ ...r.filter(y => y[0] < vfirst), ... (x.indexOf(vfirst - 1) === -1 ? [[vfirst, ...x.map(y => [y]).find(([vlast]) => ( vlast > vfirst && !x.some(v => v == vlast + 1) && x.every(v => v < vfirst || v >= vlast || x.indexOf(v + 1) > -1) )) || [] ]] : []), ...r.filter(y => y[0] > vfirst) ], [] ).map(y => y.slice(-1)[0] - y[0] >= 2 ? y[0] + '-' + y.slice(-1)[0] : y.join()).join(); console.log(solution([10])) // 10 console.log(solution([10, 10])) // 10 console.log(solution([10, 10, 9])) // 9,10 console.log(solution([12, 11])) // 11,12 console.log(solution([10, 11])) // 10,11 console.log(solution([12, 11, 10])) // 10-12 console.log(solution([9, 10, 11])) // 9-11 console.log(solution([9, 9, 10, 11])) // 9-11 console.log(solution([9, 10, 9, 11])) // 9-11 console.log(solution([10, 11, 12, 14, 15, 16, 17, 17, 9, 13, 8, 6, 5])) // 5,6,8-17 console.log(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])); // -6,-3-1,3-5,7-11,14,15,17-20 console.log(solution([6, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])); // -6,-3-1,3-11,14,15,17-20 console.log(solution([1, 10, 12, 11, -5])); // -5, 1, 10, 11, 12
lolol, when ES6 looks like Haskell 🤓
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I've challenged myself to come up with another JS solution. Highly functional, with sorting of the output but without the sort function.
Here it comes, including test cases:
lolol, when ES6 looks like Haskell 🤓