Created
July 26, 2017 09:56
-
-
Save redrabbit/85d400e88b01b6f8d0e3cb30b85b878f to your computer and use it in GitHub Desktop.
Lazy path iterator in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule RecursivePathIterator do | |
@moduledoc """ | |
This module provides a simple interface for iterating over filesystem directories. | |
""" | |
@doc """ | |
Walks the given `path` recursively. | |
""" | |
@spec walk(Path.t) :: Enumerable.t | |
def walk(path) do | |
case File.ls(path) do | |
{:ok, files} -> | |
files | |
|> Stream.map(&Path.join(path, &1)) | |
|> Stream.map(&iterate/1) | |
|> Stream.concat() | |
{:error, _reason} -> | |
[] | |
end | |
end | |
# | |
# Helpers | |
# | |
defp iterate(path) do | |
if File.dir?(path), | |
do: walk(path), | |
else: [path] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment