using System;
using System.Collections.Generic;
namespace Semmle.Util
{
///
/// A dictionary which performs an action when items are added to the dictionary.
/// The order in which keys and actions are added does not matter.
///
///
///
public class ActionMap where TKey : notnull
{
public void Add(TKey key, TValue value)
{
if (actions.TryGetValue(key, out var a))
a(value);
values[key] = value;
}
public void OnAdd(TKey key, Action action)
{
if (actions.TryGetValue(key, out var a))
{
actions[key] = a + action;
}
else
{
actions.Add(key, action);
}
if (values.TryGetValue(key, out var val))
{
action(val);
}
}
// Action associated with each key.
private readonly Dictionary> actions = new Dictionary>();
// Values associated with each key.
private readonly Dictionary values = new Dictionary();
}
}