Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created November 9, 2023 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arialdomartini/40b92b0661a4e5ab649582e2bdab9f5e to your computer and use it in GitHub Desktop.
Save arialdomartini/40b92b0661a4e5ab649582e2bdab9f5e to your computer and use it in GitHub Desktop.
TextEditor.cs
private delegate IEnumerable<string> ManipulateHistory(IEnumerable<string> history);
ManipulateHistory append(string tail) =>
history => history.Append(new[] { history.Last() + tail });
ManipulateHistory delete(int k) =>
history => history.Append(new[] { delete(history.Last(), k) });
string delete(string last, int k) => last.Substring(0, last.Length - k);
ManipulateHistory print(int k) => history =>
{
Console.WriteLine(history.Last()[k - 1].ToString());
return history;
};
ManipulateHistory undo() =>
history => history.Take(history.Length() - 1);
ManipulateHistory toCommand(string commandAndParameter)
{
var parts = commandAndParameter.Split(" ");
var command = parts[0];
return command switch
{
"1" => append(parts[1]),
"2" => delete(int.Parse(parts[1])),
"3" => print(int.Parse(parts[1])),
"4" => undo(),
};
}
[Fact]
void pass()
{
var input = new List<string>
{
"1 fg", // abcdefg
"3 6", // abcdefg
"2 5", // abcdefg ab
"4", // abcdefg
"3 7", // abcdefg
"4", // abcde
"3 4" //
};
IEnumerable<string> initial = new List<string>{"abcde"};
var result = input.Select(toCommand).Aggregate(initial, (h, c) => c(h));
Assert.Equal("abcde", result.Last());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment