Programming involves a number of tradeoffs (not limited to readability, extensibility, comprehension, brevity, and speed).
I agree that the biggest drawback about the initial solution is that another programmer (or, yourself in a few months) cannot quickly understand what is happening. It is optimized at the expense of comprehension (a mathematical formula, not its proof). To boost comprehension of the initial solution, one could add a proof sketch in a short (1–2 line) comment.
I don’t usually write with extensibility in mind. Often, I won’t need or can’t imagine ways I’ll need to adjust or generalize a snippet of code. Also, an “elegant” proof or “optimized” solution may exploit specific symmetries or conditions that do not extend well. (For example, making decisions based on
j > i relies on the end of the loop being at
i === j .)
The solution below follows an “intuitive” proof (walk backwards along the spiral until you reach the end of the last full loop). For this reason, it takes more lines of code but seems more easily comprehensible and extensible. (In fact, I initially misread your coordinates, finding out when my code didn’t pass your test cases. It was speedy and straightforward to draw out the spiral in a new orientation and update the logic accordingly.)
Probably, best practice for production-level code is somewhere in between the initial solution and the above one, depending on its purpose. At minimum, I like to give a brief sketch of “what is happening in this code”, especially if it is clever or cryptic. (My former coworker used to say he avoided writing code that was too clever, because when debugging, he had to be twice as clever. This motto prevented him from writing code he could not easily fix).
Let me know what you think. This is a neat puzzle!