Skip to content
Browse files

Add tests for lazy handling of sliding-windows, and make sure they pa…

…ss in both Niecza and Rakudo.
  • Loading branch information...
1 parent 41c3de0 commit 7a9c5492dac6ad0b22ca6b2155aee74b962f4740 @colomon committed Aug 14, 2012
Showing with 19 additions and 10 deletions.
  1. +11 −9 lib/List/Utils.pm
  2. +8 −1 t/01-sliding-window.t
View
20 lib/List/Utils.pm
@@ -1,27 +1,29 @@
module List::Utils;
+sub push-one-take-if-enough(@values is rw, $new-value, $n) {
+ @values.push($new-value);
+ @values.shift if +@values > $n;
+ if +@values == $n {
+ for @values { take $_ }
+ }
+}
+
sub sliding-window(@a, $n) is export {
my @values;
gather for @a -> $a {
- @values.push($a);
- @values.shift if +@values > $n;
- take @values if +@values == $n;
+ push-one-take-if-enough(@values, $a, $n);
}
}
sub sliding-window-wrapped(@a, $n) is export {
my @values;
gather {
for @a -> $a {
- @values.push($a);
- @values.shift if +@values > $n;
- take @values if +@values == $n;
+ push-one-take-if-enough(@values, $a, $n);
}
for ^($n-1) {
- @values.push(@a[$_]);
- @values.shift if +@values > $n;
- take @values if +@values == $n;
+ push-one-take-if-enough(@values, @a[$_], $n);
}
}
}
View
9 t/01-sliding-window.t
@@ -19,7 +19,10 @@ is ~sliding-window(1..5, 3), ~(1, 2, 3, 2, 3, 4, 3, 4, 5), "three at a time work
is ~sliding-window(([1, 'a'], [2, 'b'], [3, 'c']), 2), ~(([1, 'a'], [2, 'b']), ([2, 'b'], [3, 'c'])),
"sliding preserves internal structure";
-
+
+is ~(sliding-window(1..*, 1)[^10]), ~(1..10), "one at a time works lazily";
+is ~(sliding-window(1..*, 2)[^10]), ~(sliding-window(1..20, 2)[^10]), "two at a time works lazily";
+
is ~sliding-window-wrapped((1, 2, 3), 1), ~(1, 2, 3), "one at a time works (parcel)";
is ~sliding-window-wrapped(1..3, 1), ~(1, 2, 3), "one at a time works (range)";
# is ~sliding-window-wrapped(1...3, 1), ~(1, 2, 3), "one at a time works (series)";
@@ -42,4 +45,8 @@ is ~sliding-window-wrapped(([1, 'a'], [2, 'b'], [3, 'c']), 2),
~(([1, 'a'], [2, 'b']), ([2, 'b'], [3, 'c']), ([3, 'c'], [1, 'a'])),
"sliding preserves internal structure";
+is ~(sliding-window-wrapped(1..*, 1)[^10]), ~(1..10), "one at a time works lazily";
+is ~(sliding-window-wrapped(1..*, 2)[^10]), ~(sliding-window-wrapped(1..20, 2)[^10]), "two at a time works lazily";
+
+
done;

0 comments on commit 7a9c549

Please sign in to comment.
Something went wrong with that request. Please try again.