Skip to content

Commit f8256db

Browse files
committed
Add random color function
Add function to create terminal friendly random colors.
1 parent 943b899 commit f8256db

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

colors.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
package bunt
2222

2323
import (
24+
"image/color"
25+
"math"
26+
"math/rand"
2427
"strings"
2528

2629
colorful "github.com/lucasb-eyer/go-colorful"
@@ -344,3 +347,57 @@ func lookupColorByName(colorName string) *colorful.Color {
344347
// Give up
345348
return nil
346349
}
350+
351+
// RandomTerminalFriendlyColors creates a list of random 24 bit colors based on
352+
// the 4 bit colors that most terminals support.
353+
func RandomTerminalFriendlyColors(n int) []colorful.Color {
354+
if n < 0 {
355+
panic("size is out of bounds, must be greater than zero")
356+
}
357+
358+
f := func(i uint8) uint8 {
359+
const threshold = 128
360+
if i < threshold {
361+
return i
362+
}
363+
364+
maxFactor := .5
365+
randomFactor := 1 + (rand.Float64()*2*maxFactor - maxFactor)
366+
367+
return uint8(math.Max(
368+
math.Min(
369+
randomFactor*float64(i),
370+
255.0,
371+
),
372+
float64(threshold),
373+
))
374+
}
375+
376+
baseColors := [][]uint8{
377+
{0xAA, 0x00, 0x00},
378+
{0x00, 0xAA, 0x00},
379+
{0xFF, 0xFF, 0x00},
380+
{0x00, 0x00, 0xAA},
381+
{0xAA, 0x00, 0xAA},
382+
{0x00, 0xAA, 0xAA},
383+
{0xAA, 0xAA, 0xAA},
384+
{0xFF, 0x55, 0x55},
385+
{0x55, 0xFF, 0x55},
386+
{0xFF, 0xFF, 0x55},
387+
{0x55, 0x55, 0xFF},
388+
{0xFF, 0x55, 0xFF},
389+
{0x55, 0xFF, 0xFF},
390+
{0xFF, 0xFF, 0xFF},
391+
}
392+
393+
result := make([]colorful.Color, n)
394+
for i := 0; i < n; i++ {
395+
baseColorRGB := baseColors[i%len(baseColors)]
396+
r, g, b := baseColorRGB[0], baseColorRGB[1], baseColorRGB[2]
397+
398+
color, _ := colorful.MakeColor(color.RGBA{f(r), f(g), f(b), 0xFF})
399+
result[i] = color
400+
}
401+
402+
return result
403+
}

colors_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,4 +223,27 @@ var _ = Describe("color specific tests", func() {
223223
BeEquivalentTo(Sprint("CornflowerBlue{CornflowerBlue}")))
224224
})
225225
})
226+
227+
Context("random colors", func() {
228+
BeforeEach(func() {
229+
ColorSetting = ON
230+
TrueColorSetting = OFF
231+
})
232+
233+
AfterEach(func() {
234+
ColorSetting = AUTO
235+
TrueColorSetting = AUTO
236+
})
237+
238+
It("should create a list of random terminal friendly colors", func() {
239+
colors := RandomTerminalFriendlyColors(16)
240+
Expect(len(colors)).To(BeEquivalentTo(16))
241+
})
242+
243+
It("should panic if negative number is given", func() {
244+
Expect(func() {
245+
RandomTerminalFriendlyColors(-1)
246+
}).To(Panic())
247+
})
248+
})
226249
})

0 commit comments

Comments
 (0)