What do people think about this suggestion:

```elixir
defmodule Thing do

  def put_if(map, value_to_check, new_values) do
    Enum.reduce(map, %{},  fn
       {key, ^value_to_check}, acc -> Map.put(acc, key, Map.get(new_values, 
key))
       {key, value}, acc -> Map.put(acc, key, value)
    end)
  end

end

new_values = %{
  foo: 10,
  bar: 20
}

Thing.put_if(%{foo: nil, bar: 10}, nil, new_values)
# => %{bar: 10, foo: 10}
Thing.put_if(%{foo: false, bar: 10}, false, new_values)
# => %{bar: 10, foo: 10}
Thing.put_if(%{foo: nil, bar: 10}, false, new_values)
#=> %{bar: 10, foo: nil}
```

That would give you the ability to replace something if it was nil or false, or 
whatever you wanted?

Best

Adam

> On 23 Jul 2020, at 14:26, Zachary Daniel <[email protected]> wrote:
> 
> I would use this function pretty often if it existed :)
> 
> I'm not really a fan the `update_if` that Jose proposed because my biggest 
> use case has been "update a key, but I don't want to put a default in if it 
> doesn't exist". I think something like
> 
> `Map.update_existing(map, :key, fn value -> value * 2 end)`
> 
> You can also simulate the "update if" by putting a conditional in the 
> function like `if value != nil, ...`
> On Thursday, July 23, 2020 at 9:20:35 AM UTC-4 Riccardo Binetti wrote:
> Hi everybody,
> I would like to bring this proposal back since I just typed `def put_if` 
> again in another module :)
>  
> Being my first proposal I don't know what is the usual process, but I think 
> the discussion showed that there is some interest in this functionality.
>  
> I personally like the `update_if` proposal made by José because it's a more 
> general construct that can be useful in various situation. I wouldn't mind 
> also having a `Map.put_if` function in the Map module but I'm fine using 
> `update_if` in case.
> --
> Riccardo
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "elixir-lang-core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to [email protected] 
> <mailto:[email protected]>.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/elixir-lang-core/c9edf4de-ed6d-4d77-b7a2-1e67a113e4f1n%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/elixir-lang-core/c9edf4de-ed6d-4d77-b7a2-1e67a113e4f1n%40googlegroups.com?utm_medium=email&utm_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/0541E780-9B48-40F4-BA8D-558EE675BE2F%40a-corp.co.uk.

Reply via email to