Skip to content

Instantly share code, notes, and snippets.

@ccdschool
Last active March 31, 2016 15:45
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 ccdschool/67a9534ceb3ac2f8fbeaa916cc607113 to your computer and use it in GitHub Desktop.
Save ccdschool/67a9534ceb3ac2f8fbeaa916cc607113 to your computer and use it in GitHub Desktop.
Quellcode zum Artikel über die Refaktorisierung
using System;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
[TestFixture]
public class WordWrap
{
[Test]
public void testErzeugeZeilen() {
var worte = new[]{ "1", "22", "333", "55555"};
var lineLength = 5;
var result = WordWrap.Erzeuge_Zeilen(worte, lineLength);
Assert.AreEqual(new String[]{"1 22", "333", "55555"}, result);
}
[Test]
public void testErzeugeZeilenMitZuLangemWort() {
var worte = new[]{ "1", "22", "666666", "55555"};
var lineLength = 5;
var result = WordWrap.Erzeuge_Zeilen(worte, lineLength);
Assert.AreEqual(new String[]{"1 22", "66666", "6", "55555"}, result);
}
static string[] Erzeuge_Zeilen(string[] worte, int maxLineLength) {
return worte.Aggregate (new Ergebnistext (maxLineLength),
(text, wort) => text.Erweitern (wort))
.Zeilen;
}
class Ergebnistext {
List<string> zeilen = new List<string>();
string aktuelleZeile = "";
int maxLineLength;
public Ergebnistext(int maxLineLength) {
this.maxLineLength = maxLineLength;
}
public Ergebnistext Erweitern(string wort) {
Versuche_Wort_noch_in_Zeile_aufzunehmen (wort,
() => Versuche_zu_langes_Wort_umzubrechen (wort,
() => Neue_Zeile_mit_Wort_beginnen (wort))
);
return this;
}
void Versuche_Wort_noch_in_Zeile_aufzunehmen(string wort, Action wortPasstDochNichtInZeile) {
int futureLength = this.aktuelleZeile.Length + wort.Length + (this.aktuelleZeile.Length > 0 ? 1 : 0);
if (futureLength <= this.maxLineLength) {
this.aktuelleZeile += (this.aktuelleZeile.Length > 0 ? " " : "") + wort;
} else
wortPasstDochNichtInZeile();
}
void Versuche_zu_langes_Wort_umzubrechen(string wort, Action wortDochNichtZuLang) {
if (string.IsNullOrEmpty (this.aktuelleZeile) && wort.Length > this.maxLineLength) {
this.zeilen.Add (wort.Substring (0, this.maxLineLength));
Erweitern (wort.Substring (this.maxLineLength));
} else
wortDochNichtZuLang ();
}
void Neue_Zeile_mit_Wort_beginnen(string wort) {
this.zeilen.Add(this.aktuelleZeile);
this.aktuelleZeile = "";
Erweitern (wort);
}
public string[] Zeilen {
get {
if (string.IsNullOrEmpty (this.aktuelleZeile))
return this.zeilen.ToArray ();
else
return this.zeilen.Concat (new[]{ this.aktuelleZeile }).ToArray ();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment