Last active
December 15, 2015 01:19
-
-
Save seh/5179320 to your computer and use it in GitHub Desktop.
In response to @laboon's Twitter post concerning a predicate that determines whether a text string contains only one kind of open or close curly braces (https://twitter.com/BillLaboon/status/313085206347276288), I wanted to explore a more efficient approach—one that doesn't involve regular expressions. I may have the predicate inverted here; min…
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
package main | |
import ( | |
"strings" | |
"testing" | |
) | |
func doesntContainRune(s string, r rune) bool { | |
return !strings.ContainsRune(s, r) | |
} | |
func ContainsOneButNotOther(s string, a rune, b rune) bool { | |
// Alternately, use strings.IndexAny() and check which matched. | |
for i, r := range s { | |
switch r { | |
case a: | |
return doesntContainRune(s[i+1:], b) | |
case b: | |
return doesntContainRune(s[i+1:], a) | |
} | |
} | |
return false | |
} | |
func ContainsOnlyOneKindOfBrace(s string) bool { | |
// Alternately, use strings.IndexAny() and check which matched. | |
return ContainsOneButNotOther(s, '{', '}') | |
} | |
func checkPredicate(t *testing.T, | |
s string, expected bool, | |
clarification string) { | |
if expected != ContainsOnlyOneKindOfBrace(s) { | |
t.Errorf("%q contains %s and should count as %t.", | |
s, clarification, expected) | |
} | |
} | |
func TestNoBraces(t *testing.T) { | |
checkPredicate(t, | |
"Hello.", false, | |
"no braces") | |
} | |
func TestTwoBraces(t *testing.T) { | |
checkPredicate(t, | |
"Hello {there}.", false, | |
"two braces") | |
} | |
func TestOneOpenBrace(t *testing.T) { | |
checkPredicate(t, | |
"Hello {there.", true, | |
"one open brace and no close braces") | |
} | |
func TestOneCloseBrace(t *testing.T) { | |
checkPredicate(t, | |
"Hello }there.", true, | |
"one close brace and no open braces") | |
} | |
func TestTwoOpenBraces(t *testing.T) { | |
checkPredicate(t, | |
"Hello {there{.", true, | |
"two open braces and no close braces") | |
} | |
func TestTwoCloseBraces(t *testing.T) { | |
checkPredicate(t, | |
"Hello }there}.", true, | |
"two close braces and no open braces") | |
} | |
func TestTwoOpenAndCloseCloseBraces(t *testing.T) { | |
checkPredicate(t, | |
"Hello} {{there}.", false, | |
"two open and two close braces") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment