Skip to content

Latest commit

 

History

History
109 lines (79 loc) · 3.28 KB

File metadata and controls

109 lines (79 loc) · 3.28 KB

IndicesOf<T> class method

Project: Array Utilities Unit

Unit: DelphiDabbler.Lib.ArrayUtils

Record: TArrayUtils

Applies to: ~>0.1

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

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

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

Description

Returns the indices of all elements of an array that are 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:

  • Integer array containing all the found indexes. The array will be empty if AItem is not equal to any element of A.

Examples

Example #1

Get the indices of all elements of a byte array that are equal to a given byte value. We use an equality comparer function in this code.

procedure IndicesOf_Eg1;
var
  A: TArray<Byte>;
  Got, Expected: TArray<Integer>;
  EqComparerFn: TEqualityComparison<Byte>;
begin
  EqComparerFn := function (const L, R: Byte): Boolean
    begin
      Result := L = R;
    end;

  A := TArray<Byte>.Create(0, 3, 2, 1, 2, 3, 1, 3, 3);

  Got := TArrayUtils.IndicesOf<Byte>(3, A, EqComparerFn);
  Expected := TArray<Integer>.Create(1, 5, 7, 8);
  Assert(TArrayUtils.Equal<Integer>(Expected, Got));

  Got := TArrayUtils.IndicesOf<Byte>(4, A, EqComparerFn);
  Expected := TArray<Integer>.Create();
  Assert(TArrayUtils.Equal<Integer>(Expected, Got));
end;

Example #2

Get the indices of all elements of a string array that are the same as a given string, ignoring case. We use an equality comparer object in this code.

procedure IndicesOf_Eg2;
var
  A: TArray<string>;
  Got, Expected: TArray<Integer>;
  EqComparer: IEqualityComparer<string>;
begin
  EqComparer := TDelegatedEqualityComparer<string>.Create(
    SameText,
    function (const AValue: string): Integer
    begin
      // Don't do this unless you KNOW the hasher function won't be called
      Result := 0;
    end
  );
  A := TArray<string>.Create('foo', 'FOO', 'bar', 'baz', 'Foo');
  Got := TArrayUtils.IndicesOf<string>('foo', A, EqComparer);
  Expected := TArray<Integer>.Create(0, 1, 4);
  Assert(TArrayUtils.Equal<Integer>(Expected, Got));
end;

See Also