Created
March 29, 2016 14:14
-
-
Save Dessix/f6f192fc118fa33aead1 to your computer and use it in GitHub Desktop.
This file contains 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.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
namespace FlashFormatting { | |
public static class EnumerableX { | |
//"today is nice".Span<char>(x => x != ' ') => (['t','o','d','a','y'], [' ','i','s',' ','n','i','c','e']) | |
public static Tuple<T[], T[]> Span<T>(this IEnumerable<T> chain, Predicate<T> qualifier) { | |
if (chain == null) { | |
return null; | |
} | |
var chainArr = chain.ToArray(); | |
if (chainArr.Length == 0) { | |
return new Tuple<T[], T[]>(new T[0], new T[0]); | |
} | |
var matchingRes = chainArr.TakeWhile(item => qualifier(item)).ToArray(); | |
T[] unmatchedRes; | |
if (matchingRes.Length > 0) { | |
unmatchedRes = chainArr.Skip(matchingRes.Length).ToArray(); | |
} else { | |
unmatchedRes = chainArr; | |
} | |
return new Tuple<T[], T[]>(matchingRes, unmatchedRes); | |
} | |
//"today is nice".Span(x => x != ' ') => ("today", " is nice") | |
public static Tuple<string, string> Span(this string str, Predicate<char> qualifier) { | |
var tpl = str.Span<char>(qualifier); | |
Debug.Assert(tpl.GetType() == typeof(Tuple<char[], char[]>)); | |
return new Tuple<string, string>(new String((char[])tpl.Item1), new String((char[])tpl.Item2)); | |
} | |
//"today is nice".RSpan<char>(x => x != ' ') => (['e','c','i','n'], [' ','s','i',' ','y','a','d','o','t']) | |
public static Tuple<T[], T[]> RSpan<T>(this IEnumerable<T> chain, Predicate<T> qualifier) => chain.Reverse().Span(qualifier); | |
//"today is nice".RSpan(x => x != ' ') => ("ecin", " si yadot") | |
public static Tuple<string, string> RSpan(this string str, Predicate<char> qualifier) { | |
var tpl = str.RSpan<char>(qualifier); | |
Debug.Assert(tpl.GetType() == typeof(Tuple<char[], char[]>)); | |
return new Tuple<string, string>(new String((char[])tpl.Item1), new String((char[])tpl.Item2)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment