0

I'm trying to compare lists using an extension method that calls a comparer like so:

type HasDiff<T> = (object: T, row: any) => boolean;

 export const isListEqualToRows = <T>(objects: T[], rows: any[], hasDiffFunction: HasDiff<T>): boolean => {
  if (objects.length !== rows.length)
    return true;

  return rows.every((row, index) => {
    const object = objects[index];

    if (row.isNew) {
      return false;
    }

    return !hasDiffFunction(object, row);
  });
};

The comparison is being triggered by Angular's value changed in a ReactiveForm, not sure if relevant, but here's it:

import { isListEqualToRows } from '@core/helpers';

formGroup.valueChanges.pipe(debounceTime(debounceValue)).subscribe((changes) => {
  this.areChangesDetected = !isListEqualToRows<Person>(this.items, changes, this.hasDiff);
});

My issue is that for one object, I have a list within a list. So I'm trying to call the isListEqualToRows() method again inside:

hasDiff(item: Person, row: any): boolean {
  return item.description !== row.description
    || !isListEqualToRows<Address>(item.addresses, row.addresses, this.hasDiffAddress);
}

hasDiffAddress(item: Address, row: any): boolean {
  return item.AddressId !== row.id
    || item.AddressStreet !== row.street;
}

But I end up getting this error while running the second line of the hasDiff() method:

Cannot read properties of undefined (reading 'hasDiffAddress')

How to solve this issue?

Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79

1 Answers1

1

You are calling hasDiff without binding it to the correct this object. Since you have strict mode enabled, the this that hasDiff is referring to when invoked outside of a someObject.hasDiff(...) syntax is then undefined (without strict mode it would be the global object).

Instead of passing this.hasDiff to isListEqualToRows, you need to pass either this.hasDiff.bind(this) or (item, row) => this.hasDiff(item, row).

Alternatively, add a thisArg argument to isListEqualToRows where you pass this from the caller's scope and then invoke hasDiffFunction as hasDiffFunction.call(thisArg, object, row) instead of hasDiffFunction(object, row).

See also: How does the "this" keyword work?

CherryDT
  • 25,571
  • 5
  • 49
  • 74