Created
September 11, 2015 08:23
-
-
Save marhoily/c7cffab66e6e4aee4c2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Diagnostics; | |
using FluentAssertions; | |
using Xunit; | |
namespace SompareWithRuby | |
{ | |
[DebuggerDisplay("{Payload}")] | |
public sealed class Node<T> | |
{ | |
public T Payload; | |
public Node<T> Next; | |
public Node<T> Prev; | |
} | |
public static class LinkedListOperations | |
{ | |
public static Node<T> AsNode<T>(this T payload) | |
{ | |
return new Node<T> { Payload = payload }; | |
} | |
public static Node<T> Append<T>(this Node<T> first, T payload) | |
{ | |
var middle = AsNode(payload); | |
var last = first.Next; | |
first.Next = middle; | |
middle.Prev = first; | |
middle.Next = last; | |
if (last != null) last.Prev = middle; | |
return middle; | |
} | |
public static IEnumerable<T> EnumerateRest<T>(this Node<T> head) | |
{ | |
while (head != null) | |
{ | |
yield return head.Payload; | |
head = head.Next; | |
} | |
} | |
} | |
public sealed class LinkedListOperationsTests | |
{ | |
[Fact] | |
public void AsNode_Should_Set_Payload_Prev_Next_Correctly() | |
{ | |
var node = "blah".AsNode(); | |
node.Payload.Should().Be("blah"); | |
node.Prev.Should().BeNull(); | |
node.Next.Should().BeNull(); | |
} | |
[Fact] | |
public void Append_Should_Crete_Two_Interlinked_Nodes() | |
{ | |
var first = 1.AsNode(); | |
var second = first.Append(2); | |
first.Prev.Should().BeNull(); | |
first.Next.Should().Be(second); | |
second.Prev.Should().Be(first); | |
second.Next.Should().BeNull(); | |
} | |
[Fact] | |
public void Apped_In_The_Middle_Should_Relink_Correctly() | |
{ | |
var first = 1.AsNode(); | |
var last = first.Append(3); | |
var middle = first.Append(2); | |
first.Prev.Should().BeNull(); | |
first.Next.Should().Be(middle); | |
middle.Prev.Should().Be(first); | |
middle.Next.Should().Be(last); | |
last.Prev.Should().Be(middle); | |
last.Next.Should().BeNull(); | |
} | |
[Fact] | |
public void EnumerateRest_Should_Get_The_Element_And_All_The_Rest() | |
{ | |
var first = 1.AsNode(); | |
first.Append(2).Append(3); | |
string.Join(", ", first.EnumerateRest()) | |
.Should().Be("1, 2, 3"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment