tracks/perl5/exercises/clock/.meta/solutions/Clock.pm in trackler-2.2.1.110 vs tracks/perl5/exercises/clock/.meta/solutions/Clock.pm in trackler-2.2.1.111

- old
+ new

@@ -1,66 +1,39 @@ -package Clock; - +package Clock 1; use strict; use warnings; -use overload - "+" => "add", - "-" => "subtract", - "eq" => "equals", - '""' => "to_string"; -sub new { - my ($class, $clock) = @_; - my ($hour, $min) = @$clock; - $min = $min || "0"; +use POSIX; - my $self = bless { hour => $hour, min => $min } => $class; - $self->_normalize; - - return $self; +sub new { + my ($class, $attributes) = @_; + my $self = { + hour => $attributes->{hour} || 0, + minute => $attributes->{minute} || 0, + }; + return bless($self, $class)->BUILD; } -sub add { - my ($self, $min) = @_; - my $clock = $self->_copy; - if ($min >= 60) { - $clock->{hour} = ($clock->{hour} + int($min / 60)) % 24; - } - $clock->{min} = $clock->{min} + $min % 60; - $clock->_normalize; - return $clock; +sub time { + my ($self) = @_; + return sprintf '%02d:%02d', $self->{hour}, $self->{minute}; } -sub subtract { - my ($self, $min) = @_; - my $clock = $self->_copy; - if ($min >= 60) { - $clock->{hour} = $clock->{hour} - (int($min / 60) + 1); - $clock->{hour} = 25 + $clock->{hour} if $clock->{hour} < 0; - } - $clock->{min} = abs $clock->{min} - $min % 60; - $clock->_normalize; - return $clock; +sub add_minutes { + my ($self, $amount) = @_; + $self->{minute} += $amount; + return $self->BUILD; } -sub equals { - my ($self, $other) = @_; - return $self->to_string eq $other; +sub subtract_minutes { + my ($self, $amount) = @_; + return $self->add_minutes(-$amount); } -sub to_string { - my $self = shift; - return "$self->{hour}:$self->{min}"; +sub BUILD { + my ($self) = @_; + $self->{hour} = ( $self->{hour} + floor($self->{minute} / 60) ) % 24; + $self->{minute} %= 60; + return $self; } -sub _copy { - my $self = shift; - return __PACKAGE__->new( [$self->{hour}, $self->{min}] ); -} - -sub _normalize { - my $self = shift; - $self->{min} = "0$self->{min}" if $self->{min} < 10; - $self->{hour} = "0$self->{hour}" if $self->{hour} < 10; -} - -__PACKAGE__; +1;