0

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;
  }
Emilis
  • 152
  • 1
  • 4
  • 21
  • 3
    Seems like you want [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). – Felix Kling Jan 06 '22 at 15:42

2 Answers2

2

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];
}
zilijonas
  • 3,285
  • 3
  • 26
  • 49
0

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
});
Salmin Skenderovic
  • 1,750
  • 9
  • 22
  • if I use this answer then I get Cannot access 'relativeGroups' before initialization. Because I am trying to access it before it was created. – Emilis Jan 06 '22 at 15:53
  • my bad, just realized that relativeGroups is created locally. What are you trying to do? just remove the part with`const hasRelativeGroups ` and only return `hasDependingGroups` – Salmin Skenderovic Jan 06 '22 at 15:55