20+ years web dev | Full-stack architect | AI integrator | Passionate about clean code, APIs, and docs | Building innovative SaaS with AI | Open source enthusiast
20+ years web dev | Full-stack architect | AI integrator | Passionate about clean code, APIs, and docs | Building innovative SaaS with AI | Open source enthusiast
Here is another approach when you want to go for SPEED (maybe you need to look up coordinates very often?).
letfastMap=null;functioncomputeFastMap(in2DArray){fastMap={};for(letx=0;x<in2dArray[0].length;x++){for(lety=0;y<in2dArray.length;y++){fastMap[in2dArray[y][x]]={x,y};}}}functionfind2DCoordinate(value){if(!fastMap){thrownewError("Compute the fastMap, first!");}returnfastMap[value]||null;}
To make this work, you need to call computeFastMap(grid) at the beginning, once.
Afterwards, you can call find2DCoordinate() often but since all coordinates are pre-computed, the lookup in the
map is basically "for free" and will be VERY fast.
Good call, I hadn't worked under the assumption of needing to do multiple lookups. It reminds me of a tweet I saw of using coordinate pairs in tuples for dictionary lookups in Python twitter.com/nedbat/status/15225434...
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
If you go for speed, working without callback functions should be faster!
Maybe you can throw this against your benchmark 😅
A note:
When working with computers and coordinates I never had the case that the horizontal position was labeled with
y.So in my code, I chose to use
xfor the horizontal axis.Another difference to your function is that it returns
nullif no coordinate was found.Here is another approach when you want to go for SPEED (maybe you need to look up coordinates very often?).
To make this work, you need to call
computeFastMap(grid)at the beginning, once.Afterwards, you can call
find2DCoordinate()often but since all coordinates are pre-computed, the lookup in themap is basically "for free" and will be VERY fast.
Good call, I hadn't worked under the assumption of needing to do multiple lookups. It reminds me of a tweet I saw of using coordinate pairs in tuples for dictionary lookups in Python twitter.com/nedbat/status/15225434...