Skip to content

Instantly share code, notes, and snippets.

@coreyhaines coreyhaines/Foldit.exs
Last active Apr 4, 2018

Embed
What would you like to do?
Convert a list of paths to a tree
defmodule FolditTest do
use ExUnit.Case
doctest Foldit
def to_keyword([], keyword), do: keyword
def to_keyword([val], keyword) do
Keyword.update(keyword, nil, [val], fn existing -> [val | existing] end)
end
def to_keyword([key | val], keyword) do
Keyword.update(keyword, String.to_atom(key), to_keyword(val, []), fn existing ->
to_keyword(val, existing)
end)
end
def to_tree(list) do
list
|> Enum.map(&String.split(&1, ~r"/"))
|> List.foldl([], &to_keyword/2)
end
test "moves array into nested keyword" do
assert to_keyword(["3.md"], []) == [nil: ["3.md"]]
assert to_keyword(["1", "3.md"], []) == ["1": [nil: ["3.md"]]]
assert to_keyword(["a", "b", "3.md"], []) == [a: [b: [nil: ["3.md"]]]]
end
test "adds to existing" do
assert to_keyword(["3.md"], nil: ["1.md"]) == [nil: ["3.md", "1.md"]]
assert to_keyword(["3.md"], a: [nil: "extra.md"], nil: ["1.md"]) == [
a: [nil: "extra.md"],
nil: ["3.md", "1.md"]
]
end
test "does multiple" do
structure = [
"3.md",
"4.md"
]
assert to_tree(structure) == [nil: ["4.md", "3.md"]]
structure = [
"3.md",
"a/4.md"
]
assert to_tree(structure) == [nil: ["3.md"], a: [nil: ["4.md"]]]
structure = [
"2.md",
"3.md",
"a/4.md",
"a/5.md"
]
assert to_tree(structure) == [nil: ["3.md", "2.md"], a: [nil: ["5.md", "4.md"]]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.