Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Align semantics of Slice operator with Take #1067

Merged
merged 1 commit into from
Oct 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions Bonsai.Core/Reactive/Slice.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Xml.Serialization;
using System.ComponentModel;
Expand Down Expand Up @@ -44,17 +44,43 @@ public class Slice : Combinator
public override IObservable<TSource> Process<TSource>(IObservable<TSource> source)
{
var start = Start;
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start));
}

var step = Step;
if (step <= 0)
{
throw new ArgumentOutOfRangeException(nameof(step));
}

var stop = Stop;
return Observable.Defer(() =>
if (stop < 0)
{
throw new ArgumentOutOfRangeException(nameof(stop));
}

return (stop - start) <= 0 ? Observable.Empty<TSource>() : Observable.Create<TSource>(observer =>
{
int i = 0;
var slice = source.Where(_ =>
{
var index = i++;
return index >= start && (index - start) % step == 0;
});
return stop.HasValue ? slice.TakeWhile(_ => i < stop) : slice;
var sliceObserver = Observer.Create<TSource>(
value =>
{
var index = i++;
if (index >= start && (index - start) % step == 0)
{
observer.OnNext(value);
}

if (i >= stop)
{
observer.OnCompleted();
}
},
observer.OnError,
observer.OnCompleted);
return source.SubscribeSafe(sliceObserver);
});
}
}
Expand Down