Skip to content
Browse files

Add sliding-window-wrapped. (Better names for these would be welcome.)

  • Loading branch information...
1 parent b02035c commit 20e36bd07351fe038595b08b2d57986edceddd2f @colomon committed
Showing with 40 additions and 1 deletion.
  1. +18 −0 lib/List/Utils.pm
  2. +22 −1 t/01-sliding-window.t
View
18 lib/List/Utils.pm
@@ -10,6 +10,24 @@ sub sliding-window(@a, $n) is export(:DEFAULT) {
}
}
+sub sliding-window-wrapped(@a, $n) is export(:DEFAULT) {
+ my $a-list = @a.iterator.list;
+ my @values;
+ gather {
+ while defined(my $a = $a-list.shift) {
+ @values.push($a);
+ @values.shift if +@values > $n;
+ take @values if +@values == $n;
+ }
+
+ for ^($n-1) {
+ @values.push(@a[$_]);
+ @values.shift if +@values > $n;
+ take @values if +@values == $n;
+ }
+ }
+}
+
sub permute(@items) is export(:DEFAULT) {
sub pattern_to_permutation(@pattern, @items1) {
my @items = @items1;
View
23 t/01-sliding-window.t
@@ -3,7 +3,6 @@ use List::Utils;
plan *;
-
is ~sliding-window((1, 2, 3), 1), ~(1, 2, 3), "one at a time works (parcel)";
is ~sliding-window(1..3, 1), ~(1, 2, 3), "one at a time works (range)";
# is ~sliding-window(1...3, 1), ~(1, 2, 3), "one at a time works (series)";
@@ -22,5 +21,27 @@ 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-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)";
+
+is ~sliding-window-wrapped((1, 2, 3, 4, 5), 2), ~(1, 2, 2, 3, 3, 4, 4, 5, 5, 1), "two at a time works (parcel)";
+is ~sliding-window-wrapped(1..5, 2), ~(1, 2, 2, 3, 3, 4, 4, 5, 5, 1), "two at a time works (range)";
+
+is ~sliding-window-wrapped((1, 2, 3, 4, 5), 3), ~(1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 1, 5, 1, 2),
+ "three at a time works (parcel)";
+is ~sliding-window-wrapped(1..5, 3), ~(1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 1, 5, 1, 2),
+ "three at a time works (range)";
+
+{
+ my @a = 0..5;
+ is ~sliding-window-wrapped(@a, 2), ~(0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 0), "two at a time works on Array";
+ is ~@a, (0, 1, 2, 3, 4, 5), "Original array still okay";
+}
+
+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";
done_testing;

0 comments on commit 20e36bd

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