From: Michael Swearingen Date: Sun, 19 Oct 2008 14:42:09 +0000 (+0000) Subject: added flatten_deep with tests X-Git-Tag: 0_09^0 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=e477b088207df5ba75ee801a9ad8a0c93ced2d8f;p=gitmo%2FMoose-Autobox.git added flatten_deep with tests --- diff --git a/lib/Moose/Autobox/Array.pm b/lib/Moose/Autobox/Array.pm index 6234435..92b919b 100644 --- a/lib/Moose/Autobox/Array.pm +++ b/lib/Moose/Autobox/Array.pm @@ -121,6 +121,24 @@ sub flatten { @{$_[0]} } +sub _flatten_deep { + my @array = @_; + my $depth = CORE::pop @array; + --$depth if (defined($depth)); + + CORE::map { + (ref eq 'ARRAY') + ? (defined($depth) && $depth == -1) ? $_ : _flatten_deep( @$_, $depth ) + : $_ + } @array; + +} + +sub flatten_deep { + my ($array, $depth) = @_; + [ _flatten_deep(@$array, $depth) ]; +} + ## Junctions sub all { @@ -196,6 +214,8 @@ This is a role to describe operations on the Array type. =item B +=item B + =back =head2 Indexed implementation diff --git a/t/008_flatten.t b/t/008_flatten.t index 888024c..c2def3f 100644 --- a/t/008_flatten.t +++ b/t/008_flatten.t @@ -3,7 +3,7 @@ use strict; use warnings; -use Test::More tests => 4; +use Test::More tests => 9; use Moose::Autobox; my $array = [ qw(1 2 3 4 ) ]; @@ -33,3 +33,34 @@ is_deeply( [ \$scalar ], "flattening a reference to a scalar returns the same scalar reference", ); + +# flatten_deep on array +is_deeply( + [ 1 .. 9 ]->flatten_deep, + [ 1 .. 9 ], + "default flatten_deep on shallow array returns correct array" +); + +is_deeply( + [ [ 1 .. 3 ], [[ 4 .. 6 ]], [[[ 7 .. 9 ]]] ]->flatten_deep, + [ 1 .. 9 ], + "default flatten_deep on array with depth completely flattens array" +); + +is_deeply( + [ [ 1 .. 3 ], [[ 4 .. 6 ]], [[[ 7 .. 9 ]]] ]->flatten_deep(undef), + [ 1 .. 9 ], + "flatten_deep with an undef argument on array with depth completely flattens array" +); + +is_deeply( + [ [ 1 .. 3 ], [[ 4 .. 6 ]], [[[ 7 .. 9 ]]] ]->flatten_deep(0), + [ [ 1 .. 3 ], [[ 4 .. 6 ]], [[[ 7 .. 9 ]]] ], + "flatten_deep with depth 0 specified on array returns array unchanged" +); + +is_deeply( + [ [ 1 .. 3 ], [[ 4 .. 6 ]], [[[ 7 .. 9 ]]] ]->flatten_deep(2), + [ 1 .. 6, [ 7 .. 9 ] ], + "flatten_deep with depth specified returns correct array" +); \ No newline at end of file