有一个函数:
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);
}
此函数删除map中的元素,并添加不存在的元素。我该如何改进它?我认为这个函数很难理解。
这绝对是一个复杂的函数。
这是一个更简单的版本
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});
}
我面前没有typescript环境,所以不能确认它是否通过了所有的typescript噪音,但这将从javascript的角度工作。
我想在这里做几件事应该会有所帮助。
-
将函数拆分为多个函数,使每个函数只执行一个任务。我已经在
下面开始这样做了 -
重命名参数,使其更能描述它们所包含的内容,即,与其说"selected: bool",不如说"mapElementExists: bool"。
-
将函数重命名为更具描述性,以便读者知道这里切换的是什么
toggleMapElements(key: string, object: RegistryLayerItemGeneric, mapElementExists: boolean) {
if (mapElementExists) {
removeMapElement(key: string, object: RegistryLayerItemGeneric);
} else {
addMapElement(key: string, object: RegistryLayerItemGeneric)
}
}
removeMapElement(key: string, object: RegistryLayerItemGeneric) {
let objects = this.state.selectedRegistryObjects.get(key);
if (objects && object.ObjectId in objects) {
delete objects[object.ObjectId];
}
this.state.selectedRegistryObjects.set(key, {
...objects,
});
return;
}
addMapElement(key: string, object: RegistryLayerItemGeneric) {
const objects = {
...(this.state.selectedRegistryObjects.get(key) || {}),
...{ [object.ObjectId]: object },
};
this.state.selectedRegistryObjects.set(key, objects);
}