diff --git a/lib/faker/util.ex b/lib/faker/util.ex index d54d1d15b..b446c02b6 100644 --- a/lib/faker/util.ex +++ b/lib/faker/util.ex @@ -87,13 +87,17 @@ defmodule Faker.Util do iex> Faker.Util.list(3, &(to_string(&1))) ["0", "1", "2"] """ - @spec list(integer, (integer -> any)) :: [any] - def list(n, fun) when is_function(fun, 1) do + @spec list(non_neg_integer, (integer -> any)) :: [any] + def list(0, _) do + [] + end + + def list(n, fun) when is_function(fun, 1) and n > 0 do Enum.map(0..(n - 1), &fun.(&1)) end - @spec list(integer, (-> any)) :: [any] - def list(n, fun) when is_function(fun, 0) do + @spec list(non_neg_integer, (-> any)) :: [any] + def list(n, fun) when is_function(fun, 0) and n > 0 do Enum.map(0..(n - 1), fn _ -> fun.() end) end diff --git a/test/faker/util_test.exs b/test/faker/util_test.exs index 20ef662cd..47560d39b 100644 --- a/test/faker/util_test.exs +++ b/test/faker/util_test.exs @@ -51,4 +51,12 @@ defmodule Faker.UtilTest do assert Enum.sort(generated_value) == list end) end + + test "list/2" do + assert [0, 1, 2] = Faker.Util.list(3, & &1) + end + + test "emtpty list/2" do + assert [] = Faker.Util.list(0, fn -> raise "not called" end) + end end