Skip to content

Commit

Permalink
Add FillBackward (carries backward next observation)
Browse files Browse the repository at this point in the history
  • Loading branch information
atifaziz committed Jan 30, 2017
1 parent 95fc9cf commit ac5f9ff
Show file tree
Hide file tree
Showing 4 changed files with 251 additions and 2 deletions.
103 changes: 103 additions & 0 deletions MoreLinq.Test/FillBackwardTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using NUnit.Framework;

namespace MoreLinq.Test
{
using System.Linq;

[TestFixture]
public class FillBackwardTest
{
[Test]
public void FillBackwardWithNullSequence()
{
var e = Assert.Throws<ArgumentNullException>(() => MoreEnumerable.FillBackward<object>(null));
Assert.That(e.ParamName, Is.EqualTo("source"));
}

[Test]
public void FillBackwardWithNullPredicate()
{
var e = Assert.Throws<ArgumentNullException>(() => new object[0].FillBackward(null));
Assert.That(e.ParamName, Is.EqualTo("predicate"));
}

[Test]
public void FillBackwardWithFillSelectorButNullSequence()
{
Assert.ThrowsArgumentNullException("source", () =>
MoreEnumerable.FillBackward<object>(null, _ => false, delegate { return null; }));
}

[Test]
public void FillBackwardWithFillSelectorButNullPredicate()
{
Assert.ThrowsArgumentNullException("predicate", () =>
new object[0].FillBackward(null, delegate { return null; }));
}

[Test]
public void FillBackwardWithNullFillSelector()
{
Assert.ThrowsArgumentNullException("fillSelector", () =>
new object[0].FillBackward(_ => false, null));
}

[Test]
public void FillBackwardIsLazy()
{
new BreakingSequence<object>().FillBackward();
}

[Test]
public void FillBackward()
{
int? na = null;
var input = new[] { na, na, 1, 2, na, na, na, 3, 4, na, na };
var result = input.FillBackward();
Assert.That(result, Is.EquivalentTo(new[] { 1, 1, 1, 2, 3, 3, 3, 3, 4, na, na }));
}

[Test]
public void FillBackwardWithFillSelector()
{
var xs = new[] { 0, 0, 1, 2, 0, 0, 0, 3, 4, 0, 0 };

var result =
xs.Select(x => new { X = x, Y = x })
.FillBackward(e => e.X == 0, (nm, m) => new { m.X, nm.Y });

Assert.That(result, Is.EquivalentTo(new[]
{
new { X = 0, Y = 1 },
new { X = 0, Y = 1 },
new { X = 1, Y = 1 },
new { X = 2, Y = 2 },
new { X = 0, Y = 3 },
new { X = 0, Y = 3 },
new { X = 0, Y = 3 },
new { X = 3, Y = 3 },
new { X = 4, Y = 4 },
new { X = 0, Y = 0 },
new { X = 0, Y = 0 },
}));
}
}
}
139 changes: 139 additions & 0 deletions MoreLinq/FillBackward.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2016 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

namespace MoreLinq
{
using System;
using System.Collections.Generic;

static partial class MoreEnumerable
{
/// <summary>
/// Returns a sequence with each null reference or value in the source
/// replaced with the following non-null reference or value in
/// that sequence.
/// </summary>
/// <param name="source">The source sequence.</param>
/// <typeparam name="T">Type of the elements in the source sequence.</typeparam>
/// <returns>
/// An <see cref="IEnumerable{T}"/> with null references or values
/// replaced.
/// </returns>
/// <remarks>
/// This method uses deferred execution semantics and streams its
/// results. If references or values are null at the end of the
/// sequence then they remain null.
/// </remarks>

public static IEnumerable<T> FillBackward<T>(this IEnumerable<T> source)
{
return source.FillBackward(e => e == null);
}

/// <summary>
/// Returns a sequence with each missing element in the source replaced
/// with the following non-missing element in that sequence. An
/// additional parameter specifies a function used to determine if an
/// element is considered missing or not.
/// </summary>
/// <param name="source">The source sequence.</param>
/// <param name="predicate">The function used to determine if
/// an element in the sequence is considered missing.</param>
/// <typeparam name="T">Type of the elements in the source sequence.</typeparam>
/// <returns>
/// An <see cref="IEnumerable{T}"/> with missing values replaced.
/// </returns>
/// <remarks>
/// This method uses deferred execution semantics and streams its
/// results. If elements are missing at the end of the sequence then
/// they remain missing.
/// </remarks>

public static IEnumerable<T> FillBackward<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));

return FillBackwardImpl(source, predicate, null);
}

/// <summary>
/// Returns a sequence with each missing element in the source replaced
/// with the following non-missing element in that sequence. Additional
/// parameters specifiy two functions, one used to determine if an
/// element is considered missing or not and another to provide the
/// replacement for the missing element.
/// </summary>
/// <param name="source">The source sequence.</param>
/// <param name="predicate">The function used to determine if
/// an element in the sequence is considered missing.</param>
/// <param name="fillSelector">The function used to produce the element
/// that will replace the missing one. It receives the next non-missing
/// element as well as the current element considered missing.</param>
/// <typeparam name="T">Type of the elements in the source sequence.</typeparam>
/// An <see cref="IEnumerable{T}"/> with missing values replaced.
/// <remarks>
/// This method uses deferred execution semantics and streams its
/// results. If elements are missing at the end of the sequence then
/// they remain missing.
/// </remarks>

public static IEnumerable<T> FillBackward<T>(this IEnumerable<T> source, Func<T, bool> predicate, Func<T, T, T> fillSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
if (fillSelector == null) throw new ArgumentNullException(nameof(fillSelector));

return FillBackwardImpl(source, predicate, fillSelector);
}

static IEnumerable<T> FillBackwardImpl<T>(IEnumerable<T> source, Func<T, bool> predicate, Func<T, T, T> fillSelector)
{
List<T> blanks = null;

foreach (var item in source)
{
var isBlank = predicate(item);
if (isBlank)
{
(blanks ?? (blanks = new List<T>())).Add(item);
}
else
{
if (blanks != null)
{
foreach (var blank in blanks)
{
yield return fillSelector != null
? fillSelector(item, blank)
: item;
}

blanks.Clear();
}
yield return item;
}
}

if (blanks?.Count > 0)
{
foreach (var blank in blanks)
yield return blank;
}
}
}
}
4 changes: 2 additions & 2 deletions MoreLinq/project.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "morelinq",
"title": "MoreLINQ",
"description": "This project enhances LINQ to Objects with the following methods: Acquire, Assert, AssertCount, Batch, Cartesian, CountBy, Concat, Consume, DistinctBy, EquiZip, ExceptBy, Exclude, FillForward, Fold, ForEach, Generate, GenerateByIndex, GroupAdjacent, Incremental, Index, Interleave, Lag, Lead, MaxBy, MinBy, NestedLoops, OrderBy, OrderedMerge, Pad, Pairwise, PartialSort, PartialSortBy, Permutations, Pipe, Prepend, PreScan, Random, RandomDouble, RandomSubset, Rank, RankBy, Repeat, RunLengthEncode, Scan, Segment, SingleOrFallback, SkipUntil, Slice, SortedMerge, Split, Subsets, TagFirstLast, TakeEvery, TakeLast, TakeUntil, ThenBy, ToDataTable, ToDelimitedString, ToHashSet, Trace, TraverseBreadthFirst, TraverseDepthFirst, Windowed, ZipLongest, ZipShortest",
"description": "This project enhances LINQ to Objects with the following methods: Acquire, Assert, AssertCount, Batch, Cartesian, CountBy, Concat, Consume, DistinctBy, EquiZip, ExceptBy, Exclude, FillBackward, FillForward, Fold, ForEach, Generate, GenerateByIndex, GroupAdjacent, Incremental, Index, Interleave, Lag, Lead, MaxBy, MinBy, NestedLoops, OrderBy, OrderedMerge, Pad, Pairwise, PartialSort, PartialSortBy, Permutations, Pipe, Prepend, PreScan, Random, RandomDouble, RandomSubset, Rank, RankBy, Repeat, RunLengthEncode, Scan, Segment, SingleOrFallback, SkipUntil, Slice, SortedMerge, Split, Subsets, TagFirstLast, TakeEvery, TakeLast, TakeUntil, ThenBy, ToDataTable, ToDelimitedString, ToHashSet, Trace, TraverseBreadthFirst, TraverseDepthFirst, Windowed, ZipLongest, ZipShortest",
"language": "en-US",
"authors": [
"MoreLINQ Developers."
],
"copyright": "\u00a9 2008 Jonathan Skeet. Portions \u00a9 2009 Atif Aziz, Chris Ammerman, Konrad Rudolph. Portions \u00a9 2010 Johannes Rudolph, Leopold Bushkin. Portions \u00a9 2015 Felipe Sateler, \u201csholland\u201d. Portions \u00a9 2016 Leandro F. Vieira (leandromoh). Portions \u00a9 Microsoft. All rights reserved.",
"packOptions": {
"releaseNotes": "Adds new operators: AtMost, CountBetween, Exactly, FillForward. See also https://github.com/morelinq/MoreLINQ/wiki/API-Changes.\nObsolete: Incremental, some overloads of ToDelimitedString, SingleOrFallback (since 2.0)",
"releaseNotes": "Adds new operators: AtMost, CountBetween, Exactly, FillBackward, FillForward. See also https://github.com/morelinq/MoreLINQ/wiki/API-Changes.\nObsolete: Incremental, some overloads of ToDelimitedString, SingleOrFallback (since 2.0)",
"summary": "This project enhances LINQ to Objects with extra methods, in a manner which keeps to the spirit of LINQ.",
"owners": [
"Jon Skeet",
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ Excludes elements from a sequence starting at a given index
Returns the elements of a sequence and falls back to another if the original
sequence is empty.

### FillBackward

Returns a sequence with each null reference or value in the source replaced
with the following non-null reference or value in that sequence.

This method has 3 overloads.

### FillForward

Returns a sequence with each null reference or value in the source replaced
Expand Down

0 comments on commit ac5f9ff

Please sign in to comment.