Skip to content

Instantly share code, notes, and snippets.

@JoeCooper
Last active June 21, 2017 18:48
Show Gist options
  • Select an option

  • Save JoeCooper/032b1337b13bd9fb0eb8c0cae35c5d67 to your computer and use it in GitHub Desktop.

Select an option

Save JoeCooper/032b1337b13bd9fb0eb8c0cae35c5d67 to your computer and use it in GitHub Desktop.
//Copyright 2016 Joe Cooper
//Find the most up to date version on Gist: https://gist.github.com/JoeCooper/032b1337b13bd9fb0eb8c0cae35c5d67
using System;
using System.Collections.Generic;
namespace NobleMuffins
{
public class SetMapper<TSubject, TRepresentation>: SetMapper<TSubject, TSubject, TRepresentation>
{
public SetMapper(Func<TSubject, TRepresentation> createFunction, Action<TRepresentation> destroyFunction): base((o) => o, createFunction, destroyFunction)
{
}
}
public class SetMapper<TSubject, TKey, TRepresentation>
{
readonly Func<TSubject, TKey> keyFunction;
readonly Func<TSubject, TRepresentation> createFunction;
readonly Action<TRepresentation> destroyFunction;
readonly IDictionary<TKey, TRepresentation> extantSet;
readonly HashSet<TKey> keysToDropBuffer;
public SetMapper(Func<TSubject, TKey> keyFunction, Func<TSubject, TRepresentation> createFunction, Action<TRepresentation> destroyFunction)
{
this.keyFunction = keyFunction;
this.createFunction = createFunction;
this.destroyFunction = destroyFunction;
this.extantSet = new Dictionary<TKey, TRepresentation>();
this.keysToDropBuffer = new HashSet<TKey>();
}
public bool Map(IEnumerable<TSubject> subjects)
{
var changed = false;
keysToDropBuffer.Clear();
foreach (var kvp in extantSet)
{
keysToDropBuffer.Add(kvp.Key);
}
if (subjects != null)
{
foreach (var subject in subjects)
{
var key = keyFunction(subject);
keysToDropBuffer.Remove(key);
if (extantSet.ContainsKey(key) == false)
{
var representation = createFunction(subject);
extantSet[key] = representation;
changed = true;
}
}
}
foreach (var key in keysToDropBuffer)
{
var representation = extantSet[key];
destroyFunction(representation);
extantSet.Remove(key);
}
changed |= keysToDropBuffer.Count > 0;
return changed;
}
public TRepresentation this[TKey key]
{
get
{
return extantSet[key];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment