Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add guard clause to Deque#rotate! #5399

Merged
merged 1 commit into from Jan 2, 2018

Conversation

willcosgrove
Copy link
Contributor

@willcosgrove willcosgrove commented Dec 18, 2017

This is my first time contributing to Crystal, so please let me know if there's something I should change. I went back and forth on writing the guard clause as @size == 0 or empty?. shift and pop used @size == 0. halfs used empty?.

On one hand, the error this is fixing is due to @size being zero. But on the other hand, it makes the most intuitive sense to me that we're short circuiting the rotation when the Deque is empty, because an empty Deque (or Array or whatever) rotated is still an empty Deque.

Come to think of it, we can actually return early if @size <= 1 because a Deque of size 1 rotated any amount is still the same value.

Would you like me to change this guard clause to @size <= 1, leave it as is, or change it to @size == 0?

Fixes #5393

@konovod
Copy link
Contributor

konovod commented Dec 18, 2017

@size <= 1 is imho better - we are doing a check anyway, why not shortcut in more cases.

@RX14
Copy link
Contributor

RX14 commented Dec 18, 2017

<= 1 is probably better.

@straight-shoota
Copy link
Member

If you were checking for being empty, I think empty? should be preferred, but @size <= 1 is even better. You should also add a spec for size=1.

Rotating an empty list or a list of one does not change the list, so we
return early in those cases.  This also fixes a DivisionByZeroError when
@SiZe == 0.
@willcosgrove
Copy link
Contributor Author

Thanks for the feedback everyone! I went with the @size <= 1 like you all suggested. I also added another spec for the size == 1 case.

@sdogruyol
Copy link
Member

Welcome and congratulations for your first PR @willcosgrove 🎉

@RX14 RX14 added this to the Next milestone Jan 2, 2018
@RX14 RX14 merged commit 87126b3 into crystal-lang:master Jan 2, 2018
lukeasrodgers pushed a commit to lukeasrodgers/crystal that referenced this pull request Jan 7, 2018
Rotating an empty list or a list of one does not change the list, so we
return early in those cases.  This also fixes a DivisionByZeroError when
@SiZe == 0.
@willcosgrove willcosgrove deleted the deque-rotate-patch branch October 21, 2018 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Deque#rotate! divide by zero error
7 participants