Last active
December 20, 2015 15:28
-
-
Save sheastrickland/6153871 to your computer and use it in GitHub Desktop.
Mapping hack Dictionary - Death to switch statements!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Utils | |
{ | |
public class Transpose<TKey, TValue> : Dictionary<TKey, Func<TValue>> | |
{ | |
public IEnumerable<TValue> Intersect(IEnumerable<TKey> keys) | |
{ | |
return Map(keys).Where(IsNotDefault); | |
} | |
public IEnumerable<TValue> Union(IEnumerable<TKey> keys) | |
{ | |
return Map(keys).Union(Values.Select(func => func())); | |
} | |
public IEnumerable<TKey> SymmetricExceptWith(IEnumerable<TKey> keys) | |
{ | |
var enumerable = keys as TKey[] ?? keys.ToArray(); | |
return Keys.Except(enumerable).Union(enumerable.Except(Keys)); | |
} | |
public IEnumerable<TValue> Map(IEnumerable<TKey> keys) | |
{ | |
return keys.Select(Map); | |
} | |
public TValue Map(TKey key) | |
{ | |
return Map(key, () => default(TValue)); | |
} | |
public TValue Map(TKey key, Func<TValue> defaultValue) | |
{ | |
return HasKey(key) | |
? this[key]() | |
: defaultValue(); | |
} | |
public readonly Func<TKey, bool> HasKey; | |
public readonly Func<TValue, bool> IsDefault; | |
public readonly Func<TValue, bool> IsNotDefault; | |
public Transpose(Func<TKey, bool> hasKey = null, Func<TValue, bool> isDefault = null, Func<TValue, bool> isNotDefault = null) | |
{ | |
HasKey = hasKey ?? ContainsKey; | |
IsDefault = isDefault ?? (value => EqualityComparer<TValue>.Default.Equals(value, default(TValue))); | |
IsNotDefault = isNotDefault ?? (value => !IsDefault(value)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment