Skip to content

Commit a26100a

Browse files
committed
fix: Allow the Util.list to handle lengths of zero
1 parent 1f42d2b commit a26100a

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

lib/faker/util.ex

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,13 +87,17 @@ defmodule Faker.Util do
8787
iex> Faker.Util.list(3, &(to_string(&1)))
8888
["0", "1", "2"]
8989
"""
90-
@spec list(integer, (integer -> any)) :: [any]
91-
def list(n, fun) when is_function(fun, 1) do
90+
@spec list(non_neg_integer, (integer -> any)) :: [any]
91+
def list(0, _) do
92+
[]
93+
end
94+
95+
def list(n, fun) when is_function(fun, 1) and n > 0 do
9296
Enum.map(0..(n - 1), &fun.(&1))
9397
end
9498

95-
@spec list(integer, (-> any)) :: [any]
96-
def list(n, fun) when is_function(fun, 0) do
99+
@spec list(non_neg_integer, (-> any)) :: [any]
100+
def list(n, fun) when is_function(fun, 0) and n > 0 do
97101
Enum.map(0..(n - 1), fn _ -> fun.() end)
98102
end
99103

test/faker/util_test.exs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,12 @@ defmodule Faker.UtilTest do
5151
assert Enum.sort(generated_value) == list
5252
end)
5353
end
54+
55+
test "list/2" do
56+
assert [0, 1, 2] = Faker.Util.list(3, & &1)
57+
end
58+
59+
test "emtpty list/2" do
60+
assert [] = Faker.Util.list(0, fn -> raise "not called" end)
61+
end
5462
end

0 commit comments

Comments
 (0)