Skip to content
Advertisement

How to improve function that toggles element in map?

There is a function:

toggleSelect(key: string, object: RegistryLayerItemGeneric, selected: boolean) {
    if (selected) {
        let objects = this.state.selectedRegistryObjects.get(key);

        if (objects && object.ObjectId in objects) {
            delete objects[object.ObjectId];
        }

        this.state.selectedRegistryObjects.set(key, {
            ...objects,
        });

        return;
    }

    const objects = {
        ...(this.state.selectedRegistryObjects.get(key) || {}),
        ...{ [object.ObjectId]: object },
    };

    this.state.selectedRegistryObjects.set(key, objects);
}

This function deletes element in map and adds if not exist. How can I improve it? I think this functon complecated for understanding.

Advertisement

Answer

That is definitely a complicated function.

Here’s a simpler version

toggleSelect(key: string, object: RegistryLayerItemGeneric, selected: boolean) {
  const objects = (this.state.selectedRegistryObjects.get(key) || {});

  if (selected) {
    delete objects[object.ObjectId];  
  } else {
    objects[object.ObjectId] = object;
  }      

  this.state.selectedRegistryObjects.set(key, {...objects});
}

I don’t have a typescript environment in front of me, so can’t confirm whether it passes all the typescript noise, but this will work from a javascript perspective.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement