This is kind of a brainteaser question, since the code works perfectly fine as-is, it just irritates my aesthetic sense ever so slightly. I'm turning to Stack Overflow because my own brain is failing me right now.
Here's a snippet of code that looks up an address using the Google Maps JS API and places a marker on a map. However, sometimes the initial lookup fails, so I want to repeat the process with a different address.
geocoder.getLatLng(item.mapstring, function(point) {
if (!point) {
geocoder.getLatLng(item.backup_mapstring, function(point) {
if (!point) return;
map.setCenter(point, 13);
map.setZoom(7);
map.addOverlay(new GMarker(point));
})
return;
}
map.setCenter(point, 13);
map.setZoom(7);
map.addOverlay(new GMarker(point));
})
(The second parameter to getLatLng
is a callback function.)
Of course you can see that the three lines that center and zoom the map and add the marker are duplicated, once in the primary callback and once in the "fallback callback" (ha ha). Can you find a way to express the whole thing without any redundancy? You earn bonus points, and my adulation, if your solution works for an arbitrary number of backup map strings.