feat(batch): Impls batch merging

This commit is contained in:
William Carroll 2017-06-22 17:17:49 -04:00
parent 7cdbea0dae
commit fc4ec51166
No known key found for this signature in database
GPG Key ID: C7A53CC58D3B1F8C
2 changed files with 53 additions and 0 deletions

View File

@ -73,4 +73,18 @@ defmodule Rox.Batch do
|> :lists.reverse
|> Native.batch_write(db)
end
@doc """
Merges a list of `Batch.t` into a single `Batch.t`.
"""
@spec merge([t]) :: t
def merge(batches) do
batches
|> Enum.reduce(Batch.new, fn %Batch{operations: ops}, %Batch{operations: merge_ops} = acc ->
%{acc | operations: Enum.concat(ops, merge_ops)}
end)
end
end

39
test/rox/batch_test.exs Normal file
View File

@ -0,0 +1,39 @@
defmodule Rox.BatchTest do
use ExUnit.Case, async: true
alias Rox.Batch
describe "merge/1" do
test "stores operations in reverse order" do
batches = [
%Batch{operations: [put: {"key_a", "value_a"}]},
%Batch{operations: [put: {"key_b", "value_b"}]},
%Batch{operations: [delete: "key_a"]},
]
assert Batch.merge(batches) == %Batch{
operations: [
delete: "key_a",
put: {"key_b", "value_b"},
put: {"key_a", "value_a"},
]
}
end
test "works when a single batch contains multiple operations" do
batches = [
%Batch{operations: [put: {"key_b", "value_b"}, put: {"key_a", "value_a"}]},
%Batch{operations: [delete: "key_a"]},
]
assert Batch.merge(batches) == %Batch{
operations: [
delete: "key_a",
put: {"key_b", "value_b"},
put: {"key_a", "value_a"},
]
}
end
end
end