Skip to content

Commit 94679b1

Browse files
authored
Merge pull request #274 from axelson/fix-divide-by-zero
Fix divide by zero in Scenic.Color Thanks Jason!
2 parents bbd57e6 + 976e861 commit 94679b1

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

lib/scenic/color.ex

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -222,8 +222,17 @@ defmodule Scenic.Color do
222222
`to_hsl/1`, and `to_hsv/1` you can convert between any implicit or explicit
223223
color type to any explicit color type.
224224
"""
225+
226+
@g :color_g
227+
@ga :color_ga
228+
@rgb :color_rgb
229+
@rgba :color_rgba
230+
@hsv :color_hsv
231+
@hsl :color_hsl
225232

226-
# import IEx
233+
# Epsilon value from JS
234+
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON
235+
@epsilon 2.22044e-16
227236

228237
@type implicit ::
229238
atom
@@ -535,9 +544,9 @@ defmodule Scenic.Color do
535544
l = (max + min) / 2
536545

537546
s =
538-
case delta do
539-
0 -> 0
540-
d -> d / (1 - abs(2 * l - 1))
547+
cond do
548+
delta < @epsilon -> 0.0
549+
true -> delta / (1 - abs(2 * l - 1))
541550
end
542551

543552
{h, s * 100, l * 100}

test/scenic/color_test.exs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,12 @@ defmodule Scenic.ColorTest do
175175
assert Color.to_hsl({:color_hsl, {1.1, 1.2, 1.3}}) == {:color_hsl, {1.1, 1.2, 1.3}}
176176
end
177177

178+
test "white hsl to hsv to rgb" do
179+
assert Color.to_hsv(:white)
180+
|> Color.to_hsl()
181+
|> Color.to_rgb() == {:color_rgb, {255, 255, 255}}
182+
end
183+
178184
test "named looks right" do
179185
Color.named()
180186
|> Enum.each(fn {n, {r, g, b}} ->

0 commit comments

Comments
 (0)