How can I improve this code (efficiency, readability)?

function useChangeMapType(mapRef: mapboxgl.Map) { if (!mapRef) return;

return (mapboxStyleName: string) => { const savedSources = {}; const savedLayers = [];

// filter out mapbox styles leaving only added sources like field-boundary, crop-zones, etc.
const addedSourcesNames = Object.keys(mapRef.getStyle().sources).filter(
  sourceKey => !/mapbox:\/\/|composite/.test(sourceKey)
);

// check each layer to see if it's in addedSourcesNames
mapRef.getStyle().layers.forEach((layer: Layer) => {
  if (!addedSourcesNames.includes(layer.source)) return;

  const sourceName = layer.source;

  savedSources[sourceName] = (
    mapRef.getSource(sourceName) as Source
  ).serialize();

  savedLayers.push(layer);
});

// inside function in order to be able to remove event listener
function restoreSourcesAndLayers() {
  Object.entries(savedSources).forEach(([id, source]: SavedSources) => {
    mapRef.addSource(id, source);
  });

  savedLayers.forEach(layer => {
    mapRef.addLayer(layer);
  });

  mapRef.off('style.load', restoreSourcesAndLayers);
}

mapRef.on('style.load', restoreSourcesAndLayers);

mapRef.setStyle(`mapbox://styles/mapbox/${mapboxStyleName}`);

}; }

Posted Sep 19, 2023, 12:27 AM UTC

16
HiiiiiiPower•

My advice:

  1. It’s a bit difficult to find out what the regex expression is for. What is its purpose? What does it represent? I’d probably store the value in a variable somewhere and give it a descriptive name.

  2. I feel like the mapRef variable name is a bit misleading. Are you passing in a React ref variable (i.e. the result of calling useRef)? Or is it a reference to mapboxgl.Map?

  3. Some of the comments are superfluous, there’s no need for them, for example “check each layer…”. It’s fairly clear what is happening in the code. I don’t think they’re necessary.

  4. For ‘const sourceName = layer.source’, I would refactor to use object restructuring. Something like ‘const { source: sourceName } = layer’.

Hope this helps!

1
ForScaleOP•

Thank you!

1
nightman•
1
ForScaleOP•

Nice, thanks! I was trying to get Copilot to do it yesterday but it wasn't working out.

1