Skip to content

Instantly share code, notes, and snippets.

@IBwWG
Created February 13, 2017 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IBwWG/c730fd4a9bc9eb13bac7273f4ac3cef8 to your computer and use it in GitHub Desktop.
Save IBwWG/c730fd4a9bc9eb13bac7273f4ac3cef8 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use Test;
BEGIN { plan tests => 4 }
my $commonResult = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
joinOkay($commonResult, IBwWG::Flattener::flatten(-1, 0, 1, 2, [3], [4, [5, 6]], [[7]], 8, 9, [10, 11]));
joinOkay($commonResult, IBwWG::Flattener::flatten([[[-1]]], 0, 1, 2, [3], [4, [5, 6]], [[7], [8, [9]]], 10, 11));
joinOkay($commonResult, IBwWG::Flattener::flatten([[-1, [[[0]]]]], 1, 2, [3], [4, [[5], 6]], [[7], [8, [9]]], 10, [[[11]]]));
joinOkay($commonResult, IBwWG::Flattener::flatten([-1, 0, [1]], [2, [3, [4, [5, [6, [7, [8, [9, 10, [11]]]]]]]]]));
# Compare join results, for clearest debugging messages on failed tests.
sub joinOkay {
my ($left, @right) = @_;
ok(join(',', @$left), join(',', @right));
}
package IBwWG::Flattener;
sub flatten {
my @data = @_;
my @flattened = ();
for (@data) {
if (ref($_)) {
push @flattened, flatten(@{$_});
} else {
push @flattened, $_;
}
}
return @flattened;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment