Project: Array Utilities Unit
Unit: DelphiDabbler.Lib.ArrayUtils
Record: TArrayUtils
Applies to: ~>0.1
class function IndexOf<T>(const AItem: T; const A: array of T;
const AEqualityComparer: TEqualityComparison<T>): Integer;
overload; static;
class function IndexOf<T>(const AItem: T; const A: array of T;
const AEqualityComparer: IEqualityComparer<T>): Integer;
overload; static;
class function IndexOf<T>(const AItem: T; const A: array of T): Integer;
overload; static;Returns the first index of an element in 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:
- A function of type TEqualityComparison<T>.
- An object that supports the IEqualityComparer<T> interface.
If the parameter is omitted then the default equality comparer defined by Delphi's TEqualityComparer<T>.Default method is used.
Returns:
- The lowest index of an element of A that tests equal to AItem or
-1A contains no matching element.
Using an equality comparer function:
procedure IndexOf_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.IndexOf<Integer>(3, A, EqComparerFn) = 2);
Assert(TArrayUtils.IndexOf<Integer>(5, A, EqComparerFn) = -1);
end;Using an equality comparer object:
procedure IndexOf_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.IndexOf<string>('a', A, EqComparerObj) = 0);
Assert(TArrayUtils.IndexOf<string>('x', A, EqComparerObj) = -1);
end;