Commit 2ecc8370 authored by Matthew Holt's avatar Matthew Holt

templates: .Truncate can truncate from end of string if length is negative

parent c37ad7f6
...@@ -132,10 +132,16 @@ func (c Context) PathMatches(pattern string) bool { ...@@ -132,10 +132,16 @@ func (c Context) PathMatches(pattern string) bool {
return Path(c.Req.URL.Path).Matches(pattern) return Path(c.Req.URL.Path).Matches(pattern)
} }
// Truncate truncates the input string to the given length. If // Truncate truncates the input string to the given length.
// input is shorter than length, the entire string is returned. // If length is negative, it returns that many characters
// starting from the end of the string. If the absolute value
// of length is greater than len(input), the whole input is
// returned.
func (c Context) Truncate(input string, length int) string { func (c Context) Truncate(input string, length int) string {
if len(input) > length { if length < 0 && len(input)+length > 0 {
return input[len(input)+length:]
}
if length >= 0 && len(input) > length {
return input[:length] return input[:length]
} }
return input return input
......
...@@ -459,12 +459,36 @@ func TestTruncate(t *testing.T) { ...@@ -459,12 +459,36 @@ func TestTruncate(t *testing.T) {
inputLength: 10, inputLength: 10,
expected: "string", expected: "string",
}, },
// Test 3 - zero length
{
inputString: "string",
inputLength: 0,
expected: "",
},
// Test 4 - negative, smaller length
{
inputString: "string",
inputLength: -5,
expected: "tring",
},
// Test 5 - negative, exact length
{
inputString: "string",
inputLength: -6,
expected: "string",
},
// Test 6 - negative, bigger length
{
inputString: "string",
inputLength: -7,
expected: "string",
},
} }
for i, test := range tests { for i, test := range tests {
actual := context.Truncate(test.inputString, test.inputLength) actual := context.Truncate(test.inputString, test.inputLength)
if actual != test.expected { if actual != test.expected {
t.Errorf(getTestPrefix(i)+"Expected %s, found %s. Input was Truncate(%q, %d)", test.expected, actual, test.inputString, test.inputLength) t.Errorf(getTestPrefix(i)+"Expected '%s', found '%s'. Input was Truncate(%q, %d)", test.expected, actual, test.inputString, test.inputLength)
} }
} }
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment