Created
May 18, 2019 18:12
-
-
Save sleepiecappy/2d5ea7fcaadd279d2e94e27c2f08cfb2 to your computer and use it in GitHub Desktop.
Freecodecamp Inventory Update in Elixir
This file contains hidden or 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 FCCL.Algos.Inventory do | |
@doc """ | |
## Examples | |
iex> current = [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]] | |
iex> new = [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]] | |
iex> FCCL.Algos.Inventory.update(current, new) | |
[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]] | |
""" | |
def update(current, new) do | |
Enum.reduce(new, current, fn [qty, name] = item, acc -> | |
c = Enum.find(current, fn [_, item_name] -> item_name == name end) | |
if c == nil do | |
[item | acc] | |
else | |
[c_qty, c_name] = c | |
acc = Enum.reject(acc, fn [_, acc_name] -> acc_name == c_name end) | |
[[c_qty + qty, c_name] | acc] | |
end | |
end) | |
|> Enum.sort(fn [_, a], [_, b] -> a < b end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment