Skip to content

Latest commit

 

History

History
98 lines (71 loc) · 2.79 KB

File metadata and controls

98 lines (71 loc) · 2.79 KB

LastIndexOf<T> class method

Project: Array Utilities Unit

Unit: DelphiDabbler.Lib.ArrayUtils

Record: TArrayUtils

Applies to: ~>0.1

class function LastIndexOf<T>(const AItem: T; const A: array of T;
  const AEqualityComparer: TEqualityComparison<T>): Integer;
  overload; static;

class function LastIndexOf<T>(const AItem: T; const A: array of T;
  const AEqualityComparer: IEqualityComparer<T>): Integer;
  overload; static;

class function LastIndexOf<T>(const AItem: T; const A: array of T): Integer;
  overload; static;

Description

Returns the last index of an element of an array that is equal to a given value.

Parameters:

  • AItem - The item to be searched for.

  • A - The array to be searched.

  • AEqualityComparer - An optional function or object that is used to test the equality of two values. Used to test AItem for equality with elements of A.

    If AEqualityComparer is provided it must be one of:

    If the parameter is omitted then the default equality comparer defined by Delphi's TEqualityComparer<T>.Default method is used.

Returns:

  • The highest index of an element of A that tests equal to AItem or -1 A contains no matching element.

Examples

Example #1

Using an equality comparer function:

procedure LastIndexOf_Eg1;
var
  A: TArray<Integer>;
  EqComparerFn: TEqualityComparison<Integer>;
begin
  A := TArray<Integer>.Create(1, 2, 3, 4, 2, 3, 2);
  EqComparerFn := function(const Left, Right: Integer): Boolean
    begin
      Result := Left = Right;
    end;
  Assert(TArrayUtils.LastIndexOf<Integer>(3, A, EqComparerFn) = 5);
  Assert(TArrayUtils.LastIndexOf<Integer>(5, A, EqComparerFn) = -1);
end;

Example #2

Using an equality comparer object:

procedure LastIndexOf_Eg2;
var
  A: TArray<string>;
  EqComparerObj: IEqualityComparer<string>;
begin
  A := TArray<string>.Create('a', 'b', 'c', 'd', 'c', 'a');
  EqComparerObj := TDelegatedEqualityComparer<string>.Create(
    SameStr,
    function(const Value: string): Integer
    begin
      // only do this if you KNOW the hash function won't be called
      Result := 0;
    end
  );
  Assert(TArrayUtils.LastIndexOf<string>('a', A, EqComparerObj) = 5);
  Assert(TArrayUtils.LastIndexOf<string>('x', A, EqComparerObj) = -1);
end;

See Also