Home > Mobile >  How to remove mutation on this code Javascript?
How to remove mutation on this code Javascript?

Time:01-07

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. 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;
  }

CodePudding user response:

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];
}

CodePudding user response:

Using your code and 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
});
  •  Tags:  
  • Related