If you are a web developer or a web developer student, you have probably made at least one image carousel in your career. In fact, you've probably ...
For further actions, you may consider blocking this person and/or reporting abuse
Amazing!
You could remove the "if" splitting the handler into 2 functions or using a hashmap;
Yes, though if the we are still keeping the code DRY we would just be offsetting the if somewhere else. We wouldn't want two separate buttons that only different by which handler they call, so the button would need some logic in it to decide which handler is the right handler. That's the cool thing about programming, though. So many different ways to solve every problem.
Yeah, I wasn't saying it's wrong, and I know that the point of this post is to show the math, I just showed one of the possible solutions, but you confused me a little bit now...
What would be the difference in the pseudo-code below and why the second one wouldn't follow the DRY principle?
Nothing wrong with it at all. My point was that you still have an if statement, it's just in a different place. The only way to eliminate it would be if there were two completely different button components, one for forward and one for back, that called different code, which would then be less dry. I wasn't saying there was anything wrong with what you posted :).
Once you figure out the modulus operator, it's a pretty cool operator! A ternary operator can get rid of that last if:
(also changed currentImage to let (otherwise "Assignment to constant variable." error)
I wouldn't say a ternary is better than an
if
, especially for multi-line things like this.Thanks. I fixed it. I do that all the time.
If you create a direction enum like so:
And you're golden. Well, except when you call
handleImageChange(-7)
Solution:
currentImage = (currentImage + imageData.length + (offset % imageData.length)) % imageData.length
😊
I don't think this will work as written. You only add the number of elements to the first part if you are going backwards. This looks like it's adding it either way. If I am at the last element (2) in this example then this would return in the next index being 3 instead of 0.
Wrong. Adding either way works. 3 modulo 3 is zero, as is 6 modulo 3, 9 modulo 3 etc.
What if instead of passing a string to the function, you gave it an integer number of images to move?
Great tip!
I think you mistyped
css
in the tags and addedcs
insteadThanks. I meant cs, like computer science. :)
Oh! I thought of C sharp, but that makes more sense 😅
Pretty cool :)
This is really cool. It is always fun to see the power of simple math operations applied to the behavior of things like this and what it can drive code to do. Great post!
Pretty nifty. Previewing the next element after the modulo would be a big challenge to try without ifs.
You could just do the same thing. I.e.
nextImg = (currentImage + 1) % imageData.length;