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")
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.
Did anybody ask for some ugly code?
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 arraya.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 somepop/concat/push
, take the last array of the result array and add the current element to iti && !(a[i-1]+1-e)
is false : Initialize the next element in the result array: an array with the current element ([e]
)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 itr.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
vs7-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 elemente.length-1
is false : The current element has only one element, return a string with the array (''+[-6] will return"-6"
)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.
The problem states that the list will always go in increasing order
OK, I see now.