-
Notifications
You must be signed in to change notification settings - Fork 14
/
position.ex
64 lines (46 loc) · 1.54 KB
/
position.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
defmodule ExTermbox.Position do
@moduledoc """
Represents a position on the screen by encoding a pair of cartesian
coordinates. The origin is the top-left-most character on the screen
`(0, 0)`, while x and y increase from left to right and top to bottom,
respectively.
"""
alias __MODULE__, as: Position
@enforce_keys [:x, :y]
defstruct [:x, :y]
@type t :: %__MODULE__{x: non_neg_integer, y: non_neg_integer}
@doc """
Translates (shifts) a position by some delta x and y.
Returns a new `%Position{}`.
## Examples
iex> translate(%Position{x: 0, y: 0}, 1, 2)
%Position{x: 1, y: 2}
iex> translate(%Position{x: 10, y: 0}, -1, 0)
%Position{x: 9, y: 0}
"""
@spec translate(t, integer, integer) :: t
def translate(%Position{x: x, y: y}, dx, dy),
do: %Position{x: x + dx, y: y + dy}
@doc """
Translates a position by a delta x.
Returns a new `%Position{}`.
## Examples
iex> translate_x(%Position{x: 0, y: 0}, 2)
%Position{x: 2, y: 0}
iex> translate_x(%Position{x: 2, y: 0}, -1)
%Position{x: 1, y: 0}
"""
@spec translate_x(t, integer) :: t
def translate_x(%Position{} = pos, dx), do: translate(pos, dx, 0)
@doc """
Translates a position by a delta y.
Returns a new `%Position{}`.
## Examples
iex> translate_y(%Position{x: 0, y: 0}, 2)
%Position{x: 0, y: 2}
iex> translate_y(%Position{x: 0, y: 2}, -1)
%Position{x: 0, y: 1}
"""
@spec translate_y(t, integer) :: t
def translate_y(%Position{} = pos, dy), do: translate(pos, 0, dy)
end