kitplummer

kitplummer

Refactoring help needed - Enum.map and Map.update?

I’ve got a bit of a real world problem that I’m trying to teach myself through and am straight stuck. I’ve tried a handful of things to get to where I want to be…but just don’t have enough base knowledge to work through it. Obviously I could put this away and come back to it, but figure asking for a little help/tutoring is better. I’ve started with enumerating over a ‘categories’ list, then piping it into a Map.update, accumulating things but bah, didn’t get close.

Here’s the module:

defmodule Categories do
  def categorize!(directory, categories) do
    result = %{}
    cat1 = find_types_for_cat(directory, categories[:cat1])

    result =
      if Kernel.length(cat1[:cat1]) > 0 do
        Map.merge(result, cat1)
      else
        result
      end

    cat2 = find_types_for_cat(directory, categories[:cat2])

    result =
      if Kernel.length(cat2[:cat2]) > 0 do
        Map.merge(result, cat2)
      else
        result
      end

    cat3 = find_types_for_cat(directory, categories[:cat3])

    result =
      if Kernel.length(cat3[:cat3]) > 0 do
        Map.merge(result, cat3)
      else
        result
      end

    result
  end

  def find_types_for_cat(directory, category) do
    %{category.name => Path.wildcard("#{directory}/**/#{Category.types_to_string(category)}")}
  end
end

The struct:

defmodule Category do
  alias __MODULE__

  defstruct name: nil, types: []

  def types_to_string(category) do
    types = Enum.join(category.types, ",")
    "{" <> types <> "}"
  end
end

And here’s the tests:

defmodule CategoriesTest do
  use ExUnit.Case, async: true
  doctest Categories

  setup_all do
    category_one = %Category{name: :cat1, types: ["type1", "type1.1"]}
    category_two = %Category{name: :cat2, types: ["type2", "type2.1"]}
    category_three = %Category{name: :cat3, types: ["type3"]}

    ## TODO: Make this an extensible list of categories, no keys
    cat_map = %{:cat1 => category_one, :cat2 => category_two, :cat3 => category_three}
    [categories: cat_map]
  end

  describe "greets the world with bad Elixir" do
    test "dir1", %{categories: categories} do
      expected = %{
        cat1: ["test/dirs/dir1/type1"]
      }

      assert Categories.categorize!("test/dirs/dir1", categories) == expected
    end

    test "dir2", %{categories: categories} do
      expected = %{
        cat1: ["test/dirs/dir2/subdir1/type1", "test/dirs/dir2/type1"],
        cat2: ["test/dirs/dir2/subdir2/type2", "test/dirs/dir2/type2.1"]
      }

      assert Categories.categorize!("test/dirs/dir2", categories) == expected
    end

    test "dir3", %{categories: categories} do
      expected = %{
        cat1: ["test/dirs/dir3/subdir2/type1", "test/dirs/dir3/type1", "test/dirs/dir3/type1.1"],
        cat2: ["test/dirs/dir3/subdir3/type2", "test/dirs/dir3/type2"],
        cat3: ["test/dirs/dir3/subdir1/type3", "test/dirs/dir3/type3"]
      }

      assert Categories.categorize!("test/dirs/dir3", categories) == expected
    end
  end
end

I’ve also created a simple project to work on the problem if that’s easier to look at than pasted code blocks here.

Appreciate any help/guidance I can get. TIA.

Kit

Marked As Solved

kitplummer

kitplummer

Got it working.

Categories module:

defmodule Categories do
  @spec categorize!(any, any) :: any
  def categorize!(directory, categories) do
    Enum.reduce(categories, %{}, fn category, acc ->
      search = find_types_for_cat(directory, category)

      if Enum.empty?(search) do
        acc
      else
        Map.put(acc, category.name, search)
      end
    end)
  end

  @spec find_types_for_cat(any, atom | %{types: any}) :: [binary]
  def find_types_for_cat(directory, category) do
    Path.wildcard("#{directory}/**/#{Category.types_to_string(category)}")
  end
end

And the updated test:

defmodule CategoriesTest do
  use ExUnit.Case, async: true
  doctest Categories

  setup_all do
    category_one = %Category{name: :cat1, types: ["type1", "type1.1"]}
    category_two = %Category{name: :cat2, types: ["type2", "type2.1"]}
    category_three = %Category{name: :cat3, types: ["type3"]}
    cat_list = [category_one, category_two, category_three]
    [categories: cat_list]
  end

  describe "greets the world with bad Elixir" do
    test "dir1", %{categories: categories} do
      expected = %{
        cat1: ["test/dirs/dir1/type1"]
      }

      assert Categories.categorize!("test/dirs/dir1", categories) == expected
    end

    # @tag :skip
    test "dir2", %{categories: categories} do
      expected = %{
        cat1: ["test/dirs/dir2/subdir1/type1", "test/dirs/dir2/type1"],
        cat2: ["test/dirs/dir2/subdir2/type2", "test/dirs/dir2/type2.1"]
      }

      assert Categories.categorize!("test/dirs/dir2", categories) == expected
    end

    # @tag :skip
    test "dir3", %{categories: categories} do
      expected = %{
        cat1: ["test/dirs/dir3/subdir2/type1", "test/dirs/dir3/type1", "test/dirs/dir3/type1.1"],
        cat2: ["test/dirs/dir3/subdir3/type2", "test/dirs/dir3/type2"],
        cat3: ["test/dirs/dir3/subdir1/type3", "test/dirs/dir3/type3"]
      }

      assert Categories.categorize!("test/dirs/dir3", categories) == expected
    end
  end
end

Thanks for the pointer @kokolegorille - greatly appreciated. Will dig into Enum.reduce a bit more now.

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

Other popular topics Top

axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48475 226
New
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement