Add unary overloads for startsWith and endsWith

This commit is contained in:
Per Nordlöw 2015-10-19 21:16:49 +02:00
parent 7f24ccfeb5
commit 0b934852c3

View file

@ -1063,6 +1063,29 @@ if (isBidirectionalRange!R1 &&
}
}
/**
Checks whether the given
$(XREF_PACK_NAMED range,primitives,isInputRange,input range) ends with an
element that fulfils predicate $(D pred).
Params:
pred = Unary mandatory predicate.
doesThisEnd = The input range to check.
Returns:
$(D bool) if the first element in range $(D doesThisEnd) fulfils predicate
$(D pred), $(D false) otherwise.
*/
bool endsWith(alias pred = "a", R)(R doesThisEnd)
if (isInputRange!R &&
is(typeof(unaryFun!pred(doesThisEnd.front)) : bool))
{
return !doesThisEnd.empty && unaryFun!pred(doesThisEnd.back);
}
/// Ditto
bool endsWith(alias pred = "a == b", R, E)(R doesThisEnd, E withThis)
if (isBidirectionalRange!R &&
@ -1076,6 +1099,10 @@ if (isBidirectionalRange!R &&
///
@safe unittest
{
import std.ascii : isAlpha;
assert("abc".endsWith!(a => a.isAlpha));
assert(!"ab1".endsWith!(a => a.isAlpha));
assert(!"".endsWith!(a => a.isAlpha));
assert(endsWith("abc", ""));
assert(!endsWith("abc", "b"));
assert(endsWith("abc", "a", 'c') == 2);
@ -3296,6 +3323,29 @@ if (isInputRange!R1 &&
}
}
/**
Checks whether the given
$(XREF_PACK_NAMED range,primitives,isInputRange,input range) starts with an
element that fulfils predicate $(D pred).
Params:
pred = Unary mandatory predicate.
doesThisStart = The input range to check.
Returns:
$(D bool) if the first element in range $(D doesThisStart) fulfils predicate
$(D pred), $(D false) otherwise.
*/
bool startsWith(alias pred = "a", R)(R doesThisStart)
if (isInputRange!R &&
is(typeof(unaryFun!pred(doesThisStart.front)) : bool))
{
return !doesThisStart.empty && unaryFun!pred(doesThisStart.front);
}
/// Ditto
bool startsWith(alias pred = "a == b", R, E)(R doesThisStart, E withThis)
if (isInputRange!R &&
@ -3309,6 +3359,10 @@ if (isInputRange!R &&
///
@safe unittest
{
import std.ascii : isAlpha;
assert("abc".startsWith!(a => a.isAlpha));
assert(!"1ab".startsWith!(a => a.isAlpha));
assert(!"".startsWith!(a => a.isAlpha));
assert(startsWith("abc", ""));
assert(startsWith("abc", "a"));
assert(!startsWith("abc", "b"));