Skip to content

Instantly share code, notes, and snippets.

@mxey
Created May 1, 2013 18:20
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 mxey/5497143 to your computer and use it in GitHub Desktop.
Save mxey/5497143 to your computer and use it in GitHub Desktop.
use v5.16;
use warnings;
use Carp;
use List::Util qw(sum);
use Test::More tests => 3;
sub playlist_duration {
my ($playlist) = @_;
return seconds_to_duration(
sum(
map { duration_to_seconds($_) }
map { $_->{duration} } @{$playlist}
)
);
}
sub duration_to_seconds {
my ($duration) = @_;
if ( $duration !~ /^(\d+):([0-5]?[0-9])$/ ) {
confess "Duration invalid: $duration";
}
my ( $minutes, $seconds ) = split( /:/, $duration );
return int($minutes) * 60 + int($seconds);
}
sub seconds_to_duration {
my ($seconds) = @_;
my $minutes = int( $seconds / 60 );
$seconds = $seconds % 60;
return "$minutes:$seconds";
}
is duration_to_seconds("4:18"), 4 * 60 + 18, "duration converted to seconds";
is seconds_to_duration( 5 * 60 + 23 ), "5:23", "seconds converted to duration";
my $playlist = [
{ song => "Follow Me Back Into The Sun", duration => "4:18" },
{ song => "The City And The River", duration => "4:02" },
{ song => "Stay Over", duration => "3:17" },
{ song => "Stranger Keeper", duration => "3:30" },
{ song => "You're Not Listening", duration => "4:11" },
];
is playlist_duration($playlist), "19:18";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment