Skip to content

Commit

Permalink
Added more extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
safalin1 committed May 8, 2019
1 parent 8063896 commit 9b4789a
Show file tree
Hide file tree
Showing 7 changed files with 289 additions and 2 deletions.
1 change: 1 addition & 0 deletions Chiaki.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Chiaki/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
2 changes: 1 addition & 1 deletion Chiaki/Chiaki.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<Authors>Steven P</Authors>
<PackageProjectUrl>https://github.com/stevu236/chiaki</PackageProjectUrl>
<RepositoryUrl>https://github.com/stevu236/chiaki</RepositoryUrl>
<Description>千瑛, "thousand, crystal ball" - a set of utility libraries for .NET</Description>
<Description>千瑛, "thousand, crystal ball" - a set of utility libraries for .NET. A work in progress.</Description>
<Version>0.0.1</Version>
<PackageIconUrl>https://raw.githubusercontent.com/stevu236/chiaki/master/logo.png</PackageIconUrl>
</PropertyGroup>
Expand Down
36 changes: 36 additions & 0 deletions Chiaki/DateTimeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;

namespace Chiaki
{
/// <summary>
/// Provides extensions for System.DateTime
/// </summary>
public static class DateTimeExtensions
{
/// <summary>
/// Converts the DateTime into UNIX Timestamp format
/// </summary>
public static double ToUnixTimestamp(this DateTime input)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var diff = input - origin;

return Math.Floor(diff.TotalSeconds);
}

/// <summary>
/// Gets the date of the start of week
/// </summary>
public static DateTime GetStartOfWeek(this DateTime input, DayOfWeek startOfWeek)
{
int diff = input.DayOfWeek - startOfWeek;

if (diff < 0)
{
diff += 7;
}

return input.AddDays(-1 * diff).Date;
}
}
}
19 changes: 19 additions & 0 deletions Chiaki/DoubleExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;

namespace Chiaki
{
/// <summary>
/// Provides extensions for System.Double
/// </summary>
public static class DoubleExtensions
{
/// <summary>
/// Converts the value from a UNIX Timestamp to a DateTime.
/// </summary>
public static DateTime AsDateTimeFromUnixTimestamp(this double input)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0)
.AddSeconds(input);
}
}
}
179 changes: 179 additions & 0 deletions Chiaki/Enum.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable UnusedMember.Global

namespace Chiaki
{
/// <remarks>
/// Taken from http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5
/// </remarks>
public static class Enum<T> where T : struct
{
private static readonly IEnumerable<T> _all = Enum.GetValues(typeof(T)).Cast<T>();
private static readonly Dictionary<string, T> _insensitiveNames = _all.ToDictionary(k => Enum.GetName(typeof(T), k)?.ToUpperInvariant());
private static readonly Dictionary<string, T> _sensitiveNames = _all.ToDictionary(k => Enum.GetName(typeof(T), k));
private static readonly Dictionary<int, T> _values = _all.ToDictionary(k => Convert.ToInt32(k));
private static readonly Dictionary<T, string> _names = _all.ToDictionary(k => k, v => v.ToString());

/// <summary>
/// Gets whether or not the object provided is a valid entry in this enum.
/// </summary>
public static bool IsDefined(T value)
{
return _names.Keys.Contains(value);
}

/// <summary>
/// Gets whether or not the string value provided is a valid entry in this enum.
/// </summary>
public static bool IsDefined(string value)
{
return _sensitiveNames.Keys.Contains(value);
}

/// <summary>
/// Gets whether or not the integer value provided is a valid value within this enum.
/// </summary>
public static bool IsDefined(int value)
{
return _values.Keys.Contains(value);
}

/// <summary>
/// Gets all possible enum values in this enum.
/// </summary>
public static IEnumerable<T> GetValues()
{
return _all;
}

/// <summary>
/// Gets string representations of each value in this enum.
/// </summary>
public static string[] GetNames()
{
return _names.Values.ToArray();
}

/// <summary>
/// Gets the string representation of a specific value in this enum.
/// </summary>
public static string GetName(T value)
{
string name;
_names.TryGetValue(value, out name);
return name;
}

/// <summary>
/// Parses the string value into a enum.
/// </summary>
public static T Parse(string value)
{
T parsed;
if (!_sensitiveNames.TryGetValue(value, out parsed))
throw new ArgumentException("Value is not one of the named constants defined for the enumeration", nameof(value));
return parsed;
}

/// <summary>
/// Parses the string value into a enum, and allows you to specify whether to ignore casing.
/// </summary>
public static T Parse(string value, bool ignoreCase)
{
if (!ignoreCase)
return Parse(value);

T parsed;
if (!_insensitiveNames.TryGetValue(value.ToUpperInvariant(), out parsed))
throw new ArgumentException("Value is not one of the named constants defined for the enumeration", nameof(value));
return parsed;
}

/// <summary>
/// Tries to parses a specific enum value from a string.
/// </summary>
public static bool TryParse(string value, out T returnValue)
{
return _sensitiveNames.TryGetValue(value, out returnValue);
}

/// <summary>
/// Tries to parses a specific enum value from a string, and allows you to specify whether to ignore casing.
/// </summary>
public static bool TryParse(string value, bool ignoreCase, out T returnValue)
{
return ignoreCase
? _insensitiveNames.TryGetValue(value.ToUpperInvariant(), out returnValue)
: TryParse(value, out returnValue);
}

/// <summary>
/// Parses the string value into a nullable enum. If unable to parse, will return null.
/// </summary>
public static T? ParseOrNull(string value)
{
if (string.IsNullOrEmpty(value))
return null;

T foundValue;
if (_sensitiveNames.TryGetValue(value, out foundValue))
return foundValue;

return null;
}

/// <summary>
/// Parses the string value into a nullable enum, with the option to ignore casing. If unable to parse, will return null.
/// </summary>
public static T? ParseOrNull(string value, bool ignoreCase)
{
if (!ignoreCase)
return ParseOrNull(value);

if (string.IsNullOrEmpty(value))
return null;

T foundValue;
if (_insensitiveNames.TryGetValue(value.ToUpperInvariant(), out foundValue))
return foundValue;

return null;
}

/// <summary>
/// Attempts to cast the enum integer value into an enum value. If unable to cast, returns null.
/// </summary>
public static T? CastOrNull(int value)
{
T foundValue;
if (_values.TryGetValue(value, out foundValue))
return foundValue;

return null;
}

/// <summary>
/// Gets applied flags on an enum instance.
/// </summary>
public static IEnumerable<T> GetFlags(T flagEnum)
{
var flagInt = Convert.ToInt32(flagEnum);
return _all.Where(e => (Convert.ToInt32(e) & flagInt) != 0);
}

/// <summary>
/// Sets applied flags on an enum instance.
/// </summary>
public static T SetFlags(IEnumerable<T> flags)
{
var combined = flags.Aggregate(default(int), (current, flag) => current | Convert.ToInt32(flag));

T result;
return _values.TryGetValue(combined, out result)
? result
: default(T);
}
}
}
52 changes: 52 additions & 0 deletions Chiaki/EnumerableExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace Chiaki
{
/// <summary>
/// Provides common extensions for IEnumerables.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Creates a new Array containing the <typeparamref name="T"/> item.
/// </summary>
public static T[] AsArray<T>(this T item)
{
return new[] { item };
}

/// <summary>
/// Creates a new List containing the <typeparamref name="T"/> item.
/// </summary>
public static List<T> AsList<T>(this T item)
{
return new List<T> { item };
}

/// <summary>
/// Performs a DistinctBy the specified key instead of using an IEqualityComparer.
/// </summary>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
var seenKeys = new HashSet<TKey>();

foreach (TSource element in source)
{
if (seenKeys.Add(selector(element)))
{
yield return element;
}
}
}

/// <summary>
/// Orders the items in the IEnumerable in a random sequence.
/// </summary>
public static IEnumerable<T> OrderByRandom<T>(this IEnumerable<T> query)
{
return query.OrderBy(q => Guid.NewGuid());
}
}
}
2 changes: 1 addition & 1 deletion Chiaki/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace Chiaki
{
/// <summary>
/// Provides extensions for String
/// Provides extensions for System.String
/// </summary>
public static class StringExtensions
{
Expand Down

0 comments on commit 9b4789a

Please sign in to comment.