Skip to content

Instantly share code, notes, and snippets.

@franciscotln
Created January 4, 2018 21:47
Show Gist options
  • Save franciscotln/e45aa53344f24dbb63fd4bc7971f5c77 to your computer and use it in GitHub Desktop.
Save franciscotln/e45aa53344f24dbb63fd4bc7971f5c77 to your computer and use it in GitHub Desktop.
elixir-JS-elm
// Elixir
data = [
%{ id: 1, value: 0 },
%{ id: 2, value: 0 },
%{ id: 3, value: 0 }
]
Enum.map data, fn item ->
if item.id == 2 do
%{ item | value: item.value + 1 }
else
item
end
end
// RamdaJs
const data = [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 }
];
const idEq2 = R.propEq("id", 2);
const evolveValue = R.evolve({ value: R.inc });
R.map(R.when(idEq2, evolveValue)) (data);
// Elm
data = [
{ id = 1, value = 0 },
{ id = 2, value = 0 },
{ id = 3, value = 0 }
]
idEq2 = .id >> (==) 2
evolveValue item = { item | value = (+) 1 <| .value <| item }
when predFn projectFn data = if predFn data then projectFn data else data
List.map(when idEq2 evolveValue) data
@josevalim
Copy link

One should prefer pattern matching:

Enum.map data, fn
  %{id: 2, value: value} = item -> %{item | value: value + 1}
  item -> item
end

or if you want to do nested updates more conveniently:

Enum.map data, fn
  %{id: 2} = item -> update_in item.value, &(&1 + 1)
  item -> item
end

@franciscotln
Copy link
Author

Definitely looks better then the first if/else approach, but still personally I don't find it very reusable. You will always have to defined 2 pattern matchings where one of them actually is just the identity function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment