marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
2.99k stars 790 forks source link

Bug fix #548

Closed nilTheDev closed 3 years ago

nilTheDev commented 3 years ago

The range function would cause an infinite loop if 0 is passed explicitly as the step. If start is greater than end the control condition of the for loop in the else block will stop the loop from commencing iteration. However, if end is greater than start then the for loop will iterate infinitely causing the program to crash.

range(10, 20, 0) // this call would be fine
range(20, 10, 0) // this call would crash the program

Therefore the else block is changed to else if (step < 0). This condition will not let any for loop iterate if the step is 0.

marijnh commented 3 years ago

Given that passing 0 for step is an unreasonable request, I don't think the code should be expected to handle it --- returning the empty array is also not the right response to what the caller is asking. So I think it's reasonable for the code to hang in such a case, and prefer not to add more complexity to the solution to handle it.