Skip to content

Instantly share code, notes, and snippets.

@Dessix
Created March 29, 2016 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dessix/f6f192fc118fa33aead1 to your computer and use it in GitHub Desktop.
Save Dessix/f6f192fc118fa33aead1 to your computer and use it in GitHub Desktop.
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