Skip to content

Instantly share code, notes, and snippets.

@pjf
Created August 8, 2012 04:35
Show Gist options
  • Save pjf/3292071 to your computer and use it in GitHub Desktop.
Save pjf/3292071 to your computer and use it in GitHub Desktop.
Code for Fuzzi
#
# Instructions
#
# 1. Figure out what this function does
# 2. Write a unit test for it
# 3. Refactor for readability and efficiency
#
# NOTE: Do regular commits that show agile style iterations through the problem.
# If you prefer a different language, you can provide your solution in PHP,
# Python or Javascript too.
#
package SillyFunction;
sub group_products {
my $products = shift;
my %brand_type = ();
my $grouped_products = [];
foreach (@{$products})
{
$brand_type{$_->{brand}} ||= {};
$brand_type{$_->{brand}}->{$_->{type}} = 1;
}
foreach (sort keys %brand_type)
{
my $brand = $_;
foreach (sort keys %{$brand_type{$brand}}) {
push(@{$grouped_products}, { brand => $brand, type => $_});
}
}
$grouped_products;
}
use v5.10.0;
use Data::Dumper;
my @array = (
{ brand => 'foo', type => 'chips' },
{ brand => 'foo', type => 'fish' },
{ brand => 'bar', type => 'kitten' },
{ brand => 'bar', type => 'fish' },
);
say Dumper group_products \@array;
# Does exactly the same as:
say Dumper [ sort {
$a->{brand} cmp $b->{brand} ||
$a->{type} cmp $b->{type}
} ( @array ) ];
# and produces:
=begin data
$DATA = [
{
'type' => 'fish',
'brand' => 'bar'
},
{
'type' => 'kitten',
'brand' => 'bar'
},
{
'type' => 'chips',
'brand' => 'foo'
},
{
'type' => 'fish',
'brand' => 'foo'
}
];
=cut
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment