Skip to content

Commit

Permalink
Add SkipLast; closes #215
Browse files Browse the repository at this point in the history
  • Loading branch information
leandromoh authored and atifaziz committed Feb 23, 2017
1 parent e17bb06 commit 8716d12
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 2 deletions.
67 changes: 67 additions & 0 deletions MoreLinq.Test/SkipLastTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2017 Leandro F. Vieira (leandromoh). 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 NUnit.Framework;
using System.Linq;

namespace MoreLinq.Test
{
[TestFixture]
public class SkipLastTest
{
[Test]
public void SkipLastWithNullSequence()
{
Assert.ThrowsArgumentNullException("source", () => MoreEnumerable.SkipLast<int>(null, 1));
}

[TestCase( 0)]
[TestCase(-1)]
public void SkipLastWithCountLesserThanOne(int skip)
{
var numbers = Enumerable.Range(1, 5);

Assert.IsTrue(numbers.SkipLast(skip).SequenceEqual(numbers));
}

[Test]
public void SkipLast()
{
const int take = 100;
const int skip = 20;

var sequence = Enumerable.Range(1, take);

var expectations = sequence.Take(take - skip);

Assert.That(expectations, Is.EquivalentTo(sequence.SkipLast(skip)));
}

[TestCase(5)]
[TestCase(6)]
public void SkipLastWithSequenceShorterThanCount(int skip)
{
Assert.IsFalse(Enumerable.Range(1, 5).SkipLast(skip).Any());
}

[Test]
public void SkipLastIsLazy()
{
new BreakingSequence<object>().SkipLast(1);
}
}
}
66 changes: 66 additions & 0 deletions MoreLinq/SkipLast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2017 Leandro F. Vieira (leandromoh). 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;
using System.Linq;

static partial class MoreEnumerable
{
/// <summary>
/// Bypasses a specified number of elements at the end of the sequence.
/// </summary>
/// <param name="source">The source sequence.</param>
/// <param name="count">The number of elements to bypass at the end of the source sequence.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> containing the source sequence elements except for the bypassed ones at the end.
/// </returns>

public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source, int count)
{
if (source == null) throw new ArgumentNullException(nameof(source));

if (count < 1)
return source;

var col = source as ICollection<T>;
if (col != null)
return col.Take(col.Count - count);

return SkipLastImpl(source, count);
}

private static IEnumerable<T> SkipLastImpl<T>(IEnumerable<T> source, int count)
{
var queue = new Queue<T>(count);

foreach (var item in source)
{
if (queue.Count < count)
{
queue.Enqueue(item);
continue;
}

yield return queue.Dequeue();
queue.Enqueue(item);
}
}
}
}
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, 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, Sequence, 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, Sequence, SingleOrFallback, SkipLast, 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: Sequence. See also https://github.com/morelinq/MoreLINQ/wiki/API-Changes.",
"releaseNotes": "Adds new operators: Sequence, SkipLast. See also https://github.com/morelinq/MoreLINQ/wiki/API-Changes.",
"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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,10 @@ Returns the single element in the given sequence, or the result of executing a
fallback delegate if the sequence is empty. This method throws an exception if
there is more than one element in the sequence

### SkipLast

Bypasses a specified number of elements at the end of the sequence.

### SkipUntil

Skips items from the input sequence until the given predicate returns true
Expand Down

0 comments on commit 8716d12

Please sign in to comment.