1
0
mirror of https://github.com/mum4k/termdash.git synced 2025-04-25 13:48:50 +08:00

Creating a common numbers.Abs function for code reuse.

This commit is contained in:
Jakub Sobon 2019-01-27 22:32:06 -05:00
parent 180a652177
commit 9ca3fc8b3f
No known key found for this signature in database
GPG Key ID: F2451A77FB05D3B7
4 changed files with 39 additions and 22 deletions

View File

@ -18,6 +18,8 @@ package area
import (
"fmt"
"image"
"github.com/mum4k/termdash/numbers"
)
// Size returns the size of the provided area.
@ -76,14 +78,6 @@ func VSplit(area image.Rectangle, widthPerc int) (left image.Rectangle, right im
return left, right, nil
}
// abs returns the absolute value of x.
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// ExcludeBorder returns a new area created by subtracting a border around the
// provided area. Return the zero area if there isn't enough space to exclude
// the border.
@ -95,10 +89,10 @@ func ExcludeBorder(area image.Rectangle) image.Rectangle {
return image.ZR
}
return image.Rect(
abs(area.Min.X+1),
abs(area.Min.Y+1),
abs(area.Max.X-1),
abs(area.Max.Y-1),
numbers.Abs(area.Min.X+1),
numbers.Abs(area.Min.Y+1),
numbers.Abs(area.Max.X-1),
numbers.Abs(area.Max.Y-1),
)
}

View File

@ -22,6 +22,7 @@ import (
"github.com/mum4k/termdash/canvas/braille"
"github.com/mum4k/termdash/cell"
"github.com/mum4k/termdash/numbers"
)
// braillePixelChange represents an action on a pixel on the braille canvas.
@ -133,8 +134,8 @@ func brailleLinePoints(start, end image.Point) []image.Point {
// Implements Bresenham's line algorithm.
// https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
vertProj := abs(end.Y - start.Y)
horizProj := abs(end.X - start.X)
vertProj := numbers.Abs(end.Y - start.Y)
horizProj := numbers.Abs(end.X - start.X)
if vertProj < horizProj {
if start.X > end.X {
return lineLow(end.X, end.Y, start.X, start.Y)
@ -201,11 +202,3 @@ func lineHigh(x0, y0, x1, y1 int) []image.Point {
}
return res
}
// abs returns the absolute value of x.
func abs(x int) int {
if x < 0 {
return -x
}
return x
}

View File

@ -162,3 +162,11 @@ func RadiansToDegrees(radians float64) int {
}
return d
}
// Abs returns the absolute value of x.
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}

View File

@ -327,3 +327,25 @@ func TestRadiansToDegrees(t *testing.T) {
})
}
}
func TestAbs(t *testing.T) {
tests := []struct {
input int
want int
}{
{0, 0},
{1, 1},
{2, 2},
{-1, 1},
{-2, 2},
}
for _, tc := range tests {
t.Run(fmt.Sprintf("%d", tc.input), func(t *testing.T) {
got := Abs(tc.input)
if got != tc.want {
t.Errorf("Abs(%d) => %v, want %v", tc.input, got, tc.want)
}
})
}
}