Есть 2 задачи на ulern.me: Практика «Limited Size Stack» и Практика «Отмена», обе ссылаются на один и тот же проект, поставленную задачу выполнил, все тесты прошли успешно.
Интересно можно ли как-нибудь улучшить/оптимизировать мое решение (новичка). Так же повысить читаемость (по возможности) и по сути, сделать код максимально правильным.
Если есть - найти ошибки.
Просьба писать подробно.
Содержимое Limited Size Stack.cs:
using System;
using System.Collections.Generic;
namespace LimitedSizeStack;
public class LimitedSizeStack<T>
{
public int Count => _StackList.Count;
private bool IsFullStack => Count > _MaxCount;
private bool IsEmptyStack => Count == 0;
private readonly int _MaxCount;
private readonly LinkedList<T> _StackList = new();
public LimitedSizeStack(int maxCount)
{
_MaxCount = maxCount;
}
public void Push(T item)
{
_StackList.AddFirst(item);
if (IsFullStack)
_StackList.RemoveLast();
}
public T Pop()
{
if (IsEmptyStack)
throw new InvalidOperationException("Stack is empty");
var removedItem = _StackList.First!;
_StackList.RemoveFirst();
return removedItem.Value;
}
}
Содержимое ListModel.cs:
using System;
using System.Collections.Generic;
namespace LimitedSizeStack;
public class ListModel<T>
{
private bool HistoryActionsNoEmpty => _HistoryActions.Count > 0;
public readonly List<T> _Items;
public readonly LimitedSizeStack<Tuple<string, int, T>> _HistoryActions;
public ListModel(int undoLimit) : this(new List<T>(), undoLimit)
{
}
public ListModel(List<T> items, int undoLimit)
{
_HistoryActions = new(undoLimit);
_Items = items;
}
public void AddItem(T item)
{
_HistoryActions.Push(GetValue("AddItem", -1, item));
_Items.Add(item);
}
public void RemoveItem(int index)
{
_HistoryActions.Push(GetValue("RemoveItem", index, _Items[index]));
_Items.RemoveAt(index);
}
public bool CanUndo()
{
return HistoryActionsNoEmpty;
}
public void Undo()
{
if (CanUndo())
{
var lastEdit = _HistoryActions.Pop();
if (lastEdit.Item1 == "AddItem")
_Items.RemoveAt(_Items.Count - 1);
else
_Items.Insert(lastEdit.Item2, lastEdit.Item3);
}
}
private static Tuple<string, int, T> GetValue(string action, int index, T item)
{
return new(action, index, item);
}
}
GetValue
публичный?GetValue
тоже верное замечание, исправил. Благодарю