Skip to content

Instantly share code, notes, and snippets.

@Tewr
Created March 26, 2019 12:50
Show Gist options
  • Save Tewr/ad5af4742fccb136f0fc50bde37f1861 to your computer and use it in GitHub Desktop.
Save Tewr/ad5af4742fccb136f0fc50bde37f1861 to your computer and use it in GitHub Desktop.
Provides object extensions Map and Tap. Like LINQ Select, but for non-collections. int.Parse("5") becomes "5".Map(int.Parse).
public static class MappingExtensions
{
/// <summary>
/// Applies the specified <paramref name="transformation"/> on the <paramref name="source"/>.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="transformation"></param>
/// <returns></returns>
public static T Map<TSource, T>(this TSource source, Func<TSource, T> transformation)
{
if (transformation == null)
{
throw new ArgumentNullException(nameof(transformation));
}
return transformation(source);
}
/// <summary>
/// Applies the specified <paramref name="transformation"/> on the <paramref name="source"/> task result.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="transformation"></param>
/// <returns></returns>
public static async Task<T> Map<TSource, T>(this Task<TSource> source, Func<TSource, T> transformation)
{
var sourceResult = await source;
return sourceResult.Map(transformation);
}
/// <summary>
/// Applies the specified <paramref name="action"/> on the <paramref name="source"/>.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
/// <returns></returns>
public static TSource Tap<TSource>(this TSource source, Action<TSource> action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
action(source);
return source;
}
/// <summary>
/// Applies the specified <paramref name="action"/> on the <paramref name="source"/> task result.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
/// <returns></returns>
public static async Task<TSource> Tap<TSource>(this Task<TSource> source, Action<TSource> action)
{
var sourceResult = await source;
return sourceResult.Tap(action);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment