Keyword mapping refactoring
This commit is contained in:
@@ -96,6 +96,19 @@ type
|
||||
class function Intern(const AFields: TArray<TPair<IKeyword, T>>): IKeywordMapping<T>; static;
|
||||
end;
|
||||
|
||||
TKeywordMapping<T> = class(TInterfacedObject, IKeywordMapping<T>)
|
||||
private
|
||||
FFields: TArray<TPair<IKeyword, T>>;
|
||||
|
||||
// IKeywordMapping implementation
|
||||
function GetItems(Idx: Integer): TPair<IKeyword, T>;
|
||||
function GetFields(const Key: IKeyword): T;
|
||||
function GetCount: Integer;
|
||||
public
|
||||
constructor Create(const AFields: TArray<TPair<IKeyword, T>>);
|
||||
function IndexOf(const Key: IKeyword): Integer;
|
||||
end;
|
||||
|
||||
implementation
|
||||
|
||||
{ TKeywordRegistry.TKeyword }
|
||||
@@ -280,4 +293,49 @@ begin
|
||||
end;
|
||||
end;
|
||||
|
||||
{ TKeywordMapping }
|
||||
|
||||
constructor TKeywordMapping<T>.Create(const AFields: TArray<TPair<IKeyword, T>>);
|
||||
begin
|
||||
inherited Create;
|
||||
FFields := AFields;
|
||||
end;
|
||||
|
||||
function TKeywordMapping<T>.GetCount: Integer;
|
||||
begin
|
||||
Result := Length(FFields);
|
||||
end;
|
||||
|
||||
function TKeywordMapping<T>.GetFields(const Key: IKeyword): T;
|
||||
var
|
||||
idx: Integer;
|
||||
begin
|
||||
idx := IndexOf(Key);
|
||||
if idx < 0 then
|
||||
raise EArgumentException.CreateFmt('Field "%s" not found in dynamic record.', [Key.Name]);
|
||||
Result := FFields[idx].Value;
|
||||
end;
|
||||
|
||||
function TKeywordMapping<T>.GetItems(Idx: Integer): TPair<IKeyword, T>;
|
||||
begin
|
||||
Result := FFields[Idx];
|
||||
end;
|
||||
|
||||
function TKeywordMapping<T>.IndexOf(const Key: IKeyword): Integer;
|
||||
var
|
||||
i: Integer;
|
||||
begin
|
||||
// Linear search (O(n)). Fast enough for typical records.
|
||||
// Keyword comparison is integer-based (Idx), so this is efficient.
|
||||
for i := 0 to High(FFields) do
|
||||
begin
|
||||
if FFields[i].Key.Idx = Key.Idx then
|
||||
begin
|
||||
Result := i;
|
||||
exit;
|
||||
end;
|
||||
end;
|
||||
Result := -1;
|
||||
end;
|
||||
|
||||
end.
|
||||
|
||||
Reference in New Issue
Block a user