Skip to content

fix: Allow the Util.list to handle lengths of zero #614

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions lib/faker/util.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions test/faker/util_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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