From 2c4150a896c4eeffc904ad6bbf39962896c1c7e0 Mon Sep 17 00:00:00 2001 From: Nor Khasyatillah Date: Sat, 30 Jul 2022 01:18:19 +0700 Subject: [PATCH] new method `Name()` --- colorparser.go | 12 ++++++++++++ colorparser_test.go | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/colorparser.go b/colorparser.go index 25f5416..afae9a2 100644 --- a/colorparser.go +++ b/colorparser.go @@ -51,6 +51,18 @@ func (c Color) RGBString() string { return fmt.Sprintf("rgb(%d,%d,%d)", r, g, b) } +// Name returns name of this color if its available. +func (c Color) Name() (string, bool) { + r, g, b, _ := c.RGBA255() + rgb := [3]uint8{r, g, b} + for k, v := range namedColors { + if v == rgb { + return k, true + } + } + return "", false +} + // Implement the Go TextUnmarshaler interface func (c *Color) UnmarshalText(text []byte) error { col, err := Parse(string(text)) diff --git a/colorparser_test.go b/colorparser_test.go index 163e7ce..eee62a2 100644 --- a/colorparser_test.go +++ b/colorparser_test.go @@ -2,6 +2,7 @@ package csscolorparser import ( "image/color" + "strings" "testing" ) @@ -70,6 +71,25 @@ func TestParseColor(t *testing.T) { } func TestNamedColors(t *testing.T) { + for name, rgb := range namedColors { + c, _ := Parse(name) + r, g, b, _ := c.RGBA255() + rgb_ := [3]uint8{r, g, b} + if rgb_ != rgb { + t.Errorf("%s != %s", rgb_, rgb) + } + if name == "aqua" || name == "cyan" || name == "fuchsia" || name == "magenta" { + continue + } + if strings.Contains(name, "gray") || strings.Contains(name, "grey") { + continue + } + name_, _ := c.Name() + if name_ != name { + t.Errorf("%s != %s", name_, name) + } + } + data := [][2]string{ {"aliceblue", "#f0f8ff"}, {"bisque", "#ffe4c4"},