10 May 2020
In this blog post, I’d like to talk about a fun problem I had at work.
Without getting too nitty-gritty, here’s the gist of a problem.
How do you write a function that receives a path, such as
the.path.to.a.key, and correctly uses the dot notation to traverse an object and return the value of the key?
My solution simply
split and then
reduced the keys and returns the value, if I found it.
It’s a lot of lines of code, and not super readable, but it does work, and it is nicely documented (in my opinion).
For reference, here is lodash’s implementation.
When I asked some fellow developers at work for their ideas, I got some amazing answers! I’d particularly like to highlight this one.
Succint, to-the-point, and that
break really helps performance-wise!
You can check the performance of these two approaches in this Codepen.
Given 4 paths of varying complexity, and 1 incorrect key, here are the results:
- My approach takes 0.25ms
- My co-worker’s approach takes only 0.19ms!
Long story short - always lean on people smarter than you when trying to develop fast code! :)