[英]How to remove mutation on this code Javascript?
I managed to write code which does what I need, but I want to make it clean and remove mutation of realtiveGroups.push() but don't know how to achieve it.我设法编写了我需要的代码,但我想让它干净并删除realtiveGroups.push()的突变,但不知道如何实现它。 How to remove mutation from this code?
如何从此代码中删除突变?
export interface OfferCategory {
id: string;
name: string;
}
export interface OfferGroup {
groupId: string;
dependsOn: OfferCategory;
name: string;
rule: Rule;
products: PosProducts[];
}
function relativesFromSubscription(groups: OfferGroup[], dependingGroups: OfferGroup[]): OfferGroup[] {
const relativeGroups: OfferGroup[] = [];
groups.forEach(group => {
if (dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId)) {
relativeGroups.push(group);
}
if (relativeGroups.some(relativeGroup => group?.dependsOn?.id === relativeGroup.groupId)) {
relativeGroups.push(group);
}
});
return relativeGroups;
}
Instead of doing everything in one cycle try dividing it into a few:与其在一个周期内完成所有事情,不如尝试将其分成几个:
function relativesFromSubscription(groups: OfferGroup[], dependingGroups: OfferGroup[]): OfferGroup[] {
const groups1 = groups.filter(group => dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId));
const groups2 = groups.filter(group => groups1.some(relGroup=> group?.dependsOn?.id === relGroup.groupId));
return [...groups1, ...groups2];
}
Using your code and Array.filter使用您的代码和Array.filter
const relativeGroups: OfferGroup[] = groups.filter(group => {
return dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId) || relativeGroups.some(relativeGroup => group?.dependsOn?.id === relativeGroup.groupId)
});
Or if you want the code to be more readable you can add descriptive variables:或者,如果您希望代码更具可读性,您可以添加描述性变量:
const relativeGroups: OfferGroup[] = groups.filter(group => {
const hasDependingGroups = dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId);
const hasRelativeGroups = relativeGroups.some(relativeGroup => group?.dependsOn?.id === relativeGroup.groupId)
return hasDependingGroups || hasRelativeGroups
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.