Skip to content

Commit 5715c20

Browse files
authored
Merge pull request #269 from UnSubble/main
Optimize Color.Equals performance (O(n²) → O(n))
2 parents f72ec94 + 2f6e200 commit 5715c20

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

color.go

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -526,27 +526,24 @@ func (c *Color) Equals(c2 *Color) bool {
526526
if c == nil || c2 == nil {
527527
return false
528528
}
529+
529530
if len(c.params) != len(c2.params) {
530531
return false
531532
}
532533

534+
counts := make(map[Attribute]int, len(c.params))
533535
for _, attr := range c.params {
534-
if !c2.attrExists(attr) {
535-
return false
536-
}
536+
counts[attr]++
537537
}
538538

539-
return true
540-
}
541-
542-
func (c *Color) attrExists(a Attribute) bool {
543-
for _, attr := range c.params {
544-
if attr == a {
545-
return true
539+
for _, attr := range c2.params {
540+
if counts[attr] == 0 {
541+
return false
546542
}
543+
counts[attr]--
547544
}
548545

549-
return false
546+
return true
550547
}
551548

552549
func boolPtr(v bool) *bool {

color_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,20 @@ func TestColorEquals(t *testing.T) {
105105
}
106106
}
107107

108+
func TestColorEquals_DuplicateAttributes(t *testing.T) {
109+
ordered := New(FgRed, Bold).Add(FgRed)
110+
reordered := New(Bold, FgRed).Add(FgRed)
111+
differentCounts := New(FgRed, Bold).Add(Bold)
112+
113+
if !ordered.Equals(reordered) {
114+
t.Error("Colors with the same attributes in different orders are not equal")
115+
}
116+
117+
if ordered.Equals(differentCounts) {
118+
t.Error("Colors with different duplicate attribute counts are equal")
119+
}
120+
}
121+
108122
func TestNoColor(t *testing.T) {
109123
rb := new(bytes.Buffer)
110124
Output = rb

0 commit comments

Comments
 (0)