-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrayhelpers.pas
More file actions
96 lines (74 loc) · 2.3 KB
/
Copy patharrayhelpers.pas
File metadata and controls
96 lines (74 loc) · 2.3 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//-----------------------------------------------------------------------------------
// Helpers Package © 2026 by Alexander Tverskoy
// Licensed under the MIT License
// You may obtain a copy of the License at https://opensource.org/licenses/MIT
//-----------------------------------------------------------------------------------
unit arrayhelpers;
{$mode objfpc}{$H+}
{$modeswitch typehelpers}
interface
uses
Classes,
Math,
SysUtils;
type
TIntegerArray = array of integer;
type
TIntegerArrayHelper = type helper for TIntegerArray
public
/// Inserts a value at the specified position, shifting elements by an optional delta
procedure InsertAtPos(Pos, Value: integer; Delta: integer = 0);
/// Deletes the element at the given position from the array
procedure DeleteAtPos(Pos: integer);
/// Creates and returns an independent copy of the source array
function CloneArray: TIntegerArray;
/// Copies all elements from the source array into the destination array
procedure CopyToArray(const Dest: TIntegerArray);
end;
implementation
{TIntegerArrayHelper}
procedure TIntegerArrayHelper.InsertAtPos(Pos, Value: integer; Delta: integer = 0);
var
i, Len: integer;
begin
Len := Length(Self);
if (Pos < 0) or (Pos > Len) then
Exit; // Out of bounds
// Increase array size
SetLength(Self, Len + 1);
// Shift elements to the right
for i := Len - 1 downto Pos do
Self[i + 1] := Self[i];
// Insert new value
Self[Pos] := Value;
// Increase all following elements by Delta
for i := Pos + 1 to High(Self) do
Self[i] := Self[i] + Delta;
end;
procedure TIntegerArrayHelper.DeleteAtPos(Pos: integer);
var
i, Len: integer;
begin
Len := Length(Self);
if (Pos < 0) or (Pos >= Len) then
Exit; // Out of bounds
// Shift left
for i := Pos to Len - 2 do
Self[i] := Self[i + 1];
// Decrease array size
SetLength(Self, Len - 1);
end;
function TIntegerArrayHelper.CloneArray: TIntegerArray;
begin
Result := Copy(Self, 0, Length(Self));
end;
procedure TIntegerArrayHelper.CopyToArray(const Dest: TIntegerArray);
var
CopyCount, i: integer;
begin
// Determine how many elements to copy: take the smaller of Dest length and Src length
CopyCount := Min(Length(Dest), Length(Self));
for i := 0 to CopyCount - 1 do
Dest[i] := Self[i];
end;
end.