-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommon.ArrayUtils.pas
More file actions
60 lines (51 loc) · 1.34 KB
/
Copy pathCommon.ArrayUtils.pas
File metadata and controls
60 lines (51 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
unit Common.ArrayUtils;
interface
uses
System.Generics.Defaults;
type
TArrayUtils = record
class function IndexOf<T>( const A: TArray<T>; const Value: T ): Integer; static;
class function Remove<T>( var A: TArray<T>; const Value: T ): Boolean; static;
class function RemoveAll<T>( var A: TArray<T>; const Value: T ): Integer; static;
end;
implementation
class function TArrayUtils.IndexOf<T>( const A: TArray<T>; const Value: T ): Integer;
var
Cmp: IEqualityComparer<T>;
I: Integer;
begin
Cmp := TEqualityComparer<T>.Default;
for I := 0 to High( A ) do
if Cmp.Equals( A[ I ], Value ) then
Exit( I );
Result := -1;
end;
// Retire la première occurrence
class function TArrayUtils.Remove<T>( var A: TArray<T>; const Value: T ): Boolean;
var
Idx: Integer;
begin
Idx := IndexOf<T>( A, Value );
Result := Idx >= 0;
if Result then
Delete( A, Idx, 1 );
end;
// Retire toutes les occurrences, renvoie le nombre retiré
class function TArrayUtils.RemoveAll<T>( var A: TArray<T>; const Value: T ): Integer;
var
Cmp: IEqualityComparer<T>;
I, J: Integer;
begin
Cmp := TEqualityComparer<T>.Default;
J := 0;
for I := 0 to High( A ) do
if not Cmp.Equals( A[ I ], Value ) then
begin
if I <> J then
A[ J ] := A[ I ];
Inc( J );
end;
Result := Length( A ) - J;
SetLength( A, J );
end;
end.