Skip to content

Instantly share code, notes, and snippets.

@seh
Last active Dec 15, 2015
Embed
What would you like to do?
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…
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