2 ms·
This is almost a great demonstration of how refactoring code into pure functions can help with robustness and maintainability To get all the way there you need
by brundolf 4y ago
This is almost a great demonstration of how refactoring code into pure functions can help with robustness and maintainability
To get all the way there you need a couple tweaks:
function update(time: number, random: number): { left: number, top: number } {
First, the random number for each render gets pulled out into a function argument, making the contents of the function deterministic
Second, the function now returns left/top instead of setting them onto an element directly
(we may also now want to rename it from "update" to something like "getPosition" to reflect its new role)
With these two changes, this function is now extremely easy to test, apply to other use-cases, etc. It's nothing but input/output. This is something we in general should try to do with as much business logic as possible.
(One caveat that's specific to animations: returning these values as an object instead of setting them directly may, in JavaScript, result in doing allocations on every frame which may harm performance. But this is only really a concern in real-time domains like graphics, where the function may be called 60+ times per second. It could also be avoided by splitting this into two separate functions, one for `top` and one for `left`, so the numbers don't have to be bundled up into an object to be returned.)
EDIT: I just noticed it grabs the window and logo dimensions directly too. Those would also need to be pulled up into function arguments for this to be a pure function
- danhau 4y ago> It could also be avoided by splitting this into two separate functions, one for `top` and one for `left`, so the numbers don't have to be bundled up into an object to be returned. This is probably a bad idea for performance too, as you'll potentially be doing lots of calculations twice.
- brundolf 4y agoIn some situations, though in this one I think they're actually totally independent But ofc in a real scenario where this matters you'd only want to optimize based on what a profiler says