Advertisement
VssA

Untitled

Feb 16th, 2024
959
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace TodoApplication
  5. {
  6.     class History<TItem>
  7.     {
  8.         public History(Operation operation, int index, TItem item)
  9.         {
  10.             Operation = operation;
  11.             Index = index;
  12.             Item = item;
  13.         }
  14.  
  15.         public Operation Operation;
  16.         public int Index;
  17.         public TItem Item;
  18.     }
  19.  
  20.     public enum Operation
  21.     {
  22.         Add,
  23.         Remove
  24.     }
  25.  
  26.     public class ListModel<TItem>
  27.     {
  28.         public List<TItem> Items { get; }
  29.         public readonly int Limit;
  30.         private readonly LimitedSizeStack<History<TItem>> operationStack;
  31.  
  32.         public ListModel(int limit)
  33.         {
  34.             Items = new List<TItem>();
  35.             Limit = limit;
  36.             operationStack = new LimitedSizeStack<History<TItem>>(limit);
  37.         }
  38.  
  39.         public void AddItem(TItem item)
  40.         {
  41.             var newAddCommand = new History<TItem>(Operation.Add, Items.Count, item);
  42.             operationStack.Push(newAddCommand);
  43.             Items.Add(item);
  44.         }
  45.  
  46.         public void RemoveItem(int index)
  47.         {
  48.             var newRemoveCommand = new History<TItem>(Operation.Remove, index, Items[index]);
  49.             operationStack.Push(newRemoveCommand);
  50.             Items.RemoveAt(index);
  51.         }
  52.  
  53.         public bool CanUndo()
  54.         {
  55.             return operationStack.Count > 0;
  56.         }
  57.  
  58.         public void Undo()
  59.         {
  60.             History<TItem> deepestCommand = operationStack.Pop();
  61.  
  62.             switch (deepestCommand.Operation)
  63.             {
  64.                 case Operation.Add:
  65.                     Items.RemoveAt(deepestCommand.Index);
  66.                     break;
  67.                 case Operation.Remove:
  68.                     Items.Insert(deepestCommand.Index, deepestCommand.Item);
  69.                     break;
  70.             }
  71.         }
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement