This is a new site that's currently running on alpha code. There are going to be bugs. If you discover any, please report them on the site's issues page (GitHub account required). Thanks.
Warning: Many URLs are going to change. Refer to the README file to discover which library project's documentation has been completed.
Project: Array Utilities Unit
Unit: DelphiDabbler.Lib.ArrayUtils
Record: TArrayUtils
Applies to: ~>0.1
class function OccurrencesOf<T>(const AItem: T; const A: array of T;
const AEqualityComparer: TEqualityComparison<T>): Integer;
overload; static;
class function OccurrencesOf<T>(const AItem: T; const A: array of T;
const AEqualityComparer: IEqualityComparer<T>): Integer;
overload; static;
class function OccurrencesOf<T>(const AItem: T;
const A: array of T): Integer;
overload; static;
Returns the number of 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:
Using an equality comparer function:
procedure OccurrencesOf_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.OccurrencesOf<Integer>(2, A, EqComparerFn) = 3);
Assert(TArrayUtils.OccurrencesOf<Integer>(5, A, EqComparerFn) = 0);
end;
Using an equality comparer object:
procedure OccurrencesOf_Eg2;
var
A: TArray<string>;
EqComparerObj: IEqualityComparer<string>;
begin
A := TArray<string>.Create('A', 'B', 'C', 'd', 'c', 'a');
EqComparerObj := TDelegatedEqualityComparer<string>.Create(
SameText,
function(const Value: string): Integer
begin
// only do this if you KNOW the hash function won't be called
Result := 0;
end
);
Assert(TArrayUtils.OccurrencesOf<string>('C', A, EqComparerObj) = 2);
Assert(TArrayUtils.OccurrencesOf<string>('x', A, EqComparerObj) = 0);
end;