Created
December 6, 2017 13:58
-
-
Save MikeMKH/751a6ca7542907954d5de8bd8e8028e4 to your computer and use it in GitHub Desktop.
Rot 13 kata in C# with xUnit in one line.
This file contains hidden or 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; | |
using System.Linq; | |
namespace Cipher | |
{ | |
public class Rot13 | |
{ | |
public static string Encode(string text) | |
=> new string( | |
text.ToCharArray() | |
.Select(c => char.IsLetter(c) ? | |
char.IsLower(c) ? | |
(char)((c - 'a' + 13) % 26 + 'a') | |
: (char)((c - 'A' + 13) % 26 + 'A') | |
: c | |
).ToArray()); | |
} | |
} |
This file contains hidden or 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; | |
using Xunit; | |
namespace Cipher.Tests | |
{ | |
public class Rot13Tests | |
{ | |
[Fact] | |
public void GivenEmptyItMustReturnEmpty() | |
{ | |
var actual = Rot13.Encode(string.Empty); | |
Assert.True(string.IsNullOrEmpty(actual)); | |
} | |
[Theory] | |
[InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "NOPQRSTUVWXYZABCDEFGHIJKLM")] | |
[InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")] | |
[InlineData("Why did the chicken cross the road?", "Jul qvq gur puvpxra pebff gur ebnq?")] | |
[InlineData("Gb trg gb gur bgure fvqr!", "To get to the other side!")] | |
public void GivenValueMustEncodeToExpectedValue(string given, string expected) | |
=> Assert.Equal(expected, Rot13.Encode(given)); | |
} | |
} |
Love this! To make it even shorter - you can ditch text.ToCharArray().Select use Select right off of the string.
> "ABC".ToCharArray().Select(c => (char)((c - 'A' + 13) % 26 + 'A')).ToArray()
> char[3] { 'N', 'O', 'P' }
> "ABC".Select(c => (char)((c - 'A' + 13) % 26 + 'A')).ToArray()
> char[3] { 'N', 'O', 'P' }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@MikeMKH too late.