View Source Chord.Delta (Chord v0.1.2)
Provides utilities for calculating, merging, and formatting context deltas.
This module contains functions to:
- Compute the differences (deltas) between two contexts.
- Merge multiple deltas into a single representation.
- Format deltas for communication or storage purposes.
The formatting of deltas is customizable. Developers can define their own formatter module
implementing the Chord.Delta.Formatter.Behaviour and configure it in their application.
By default, the library uses Chord.Delta.Formatter.Default.
Summary
Functions
Calculates the delta between two contexts.
Formats a delta map for external communication or storage.
Merges a list of deltas into a single delta.
Functions
Calculates the delta between two contexts.
Given a current_context and a new_context, this function determines the differences:
- Keys present in
new_contextbut not incurrent_contextare marked as:added. - Keys present in both but with differing values are marked as
:modified. - Keys present in
current_contextbut absent innew_contextare marked as:removed.
Parameters
current_context(map): The original context.new_context(map): The updated context.
Returns
- (map): A map representing the delta, where each key maps to a change descriptor.
Example
iex> current_context = %{a: 1, b: 2, c: 3}
iex> new_context = %{a: 1, b: 5, d: 4}
iex> Chord.Delta.calculate_delta(current_context, new_context)
%{
b: %{action: :modified, old_value: 2, value: 5},
c: %{action: :removed},
d: %{action: :added, value: 4}
}
Formats a delta map for external communication or storage.
Uses the configured delta formatter to transform the delta map into a desired format.
By default, it uses Chord.Delta.Formatter.Default.
Parameters
delta(map): The delta to format.context_id(any): The context associated with the delta.
Returns
- (list): The formatted delta, as determined by the formatter module.
Example
iex> delta = %{a: %{action: :added, value: 1}, b: %{action: :removed}}
iex> Chord.Delta.format_delta(delta, "game:1")
[
%{key: :a, action: :added, value: 1, context: "game:1"},
%{key: :b, action: :removed, context: "game:1"}
]
Merges a list of deltas into a single delta.
Combines multiple delta maps to produce a unified view of changes. The merging logic ensures:
- If any delta marks a key as
:removed, it takes precedence. - If multiple deltas modify the same key, the
old_valueis taken from the first modification, and thevaluefrom the last. - Otherwise, the latest change is retained.
Parameters
delta_list(list of maps): A list of deltas to merge.
Returns
- (map): A single delta representing the merged changes.
Example
iex> delta1 = %{a: %{action: :added, value: 1}, b: %{action: :modified, old_value: 2, value: 3}}
iex> delta2 = %{b: %{action: :removed}, c: %{action: :added, value: 4}}
iex> Chord.Delta.merge_deltas([delta1, delta2])
%{
a: %{action: :added, value: 1},
b: %{action: :removed},
c: %{action: :added, value: 4}
}