DEV Community

Discussion on: Daily Challenge #93 - Range Extraction

Collapse
 
ynndvn profile image
La blatte • Edited

Did anybody ask for some ugly code?

f=a=>(r=[],a.map((e,i)=>i&&!(a[i-1]+1-e)?r.push(r.pop().concat(e)):r.push([e])),r.map(e=>e.length-1?`${e[0]}-${e.pop()}`:''+e))

How does it work? Well it's a oneshot, I didn't take any time before writing it, I guess it should be way easier:

  • r[]: Initialize the result array
  • a.map : In this one, a ternary operation is used in order to handle two cases:
    • i && !(a[i-1]+1-e) is true : We are not in the first element, and the previous one is equal to "current one minus 1". In this case, with some pop/concat/push, take the last array of the result array and add the current element to it
    • i && !(a[i-1]+1-e) is false : Initialize the next element in the result array: an array with the current element ([e])
  • With the input example, r is equal to this value at this stage: [[-6], [-3, -2, -1, 0, 1], [3, 4, 5], [7, 8, 9, 10, 11], [14, 15], [17, 18, 19, 20]], we need to format it
  • r.map : In this one, e will be equal to each array. We will need to differentiate array with a length of 1 and the others, as their notation is different (-6 vs 7-11). To do this, we will use another ternary:
    • e.length-1 is true : The current element has more than one element, build a string with the first and last element
    • e.length-1 is false : The current element has only one element, return a string with the array (''+[-6] will return "-6")
Collapse
 
erezwanderman profile image
erezwanderman • Edited

You are grouping groups of 2. You should only be grouping 3 or more consecutive numbers.
Also, you are not sorting the list, so it will fail on unordered lists.

Collapse
 
thepeoplesbourgeois profile image
Josh

The problem states that the list will always go in increasing order

Thread Thread
 
erezwanderman profile image
erezwanderman

OK, I see now.