check both days remaining types
[engit/Iron-Munger.git] / lib / IronMunger / Calculate.pm
CommitLineData
ac04ccd9 1package IronMunger::Calculate;
2
3use strict;
4use warnings;
66bdbe82 5use List::Util qw(min);
38827ef4 6use autobox;
38efa3f1 7use autobox::DateTime::Duration;
f79d4b5c 8use signatures;
67e9aef2 9
a7b549f9 10use Sub::Exporter -setup => {
11 exports => [
12 qw(successful_sequential_posts time_remaining_to_post)
13 ]
14};
15
66bdbe82 16sub day_diff ($dt1, $dt2) {
17 $dt1 = $dt1->at if $dt1->isa('IronMunger::Post');
18 $dt2 = $dt2->at if $dt2->isa('IronMunger::Post');
19 $dt1->delta_days($dt2)->delta_days;
20}
21
38efa3f1 22sub check_post_gap ($aperture, $days, @posts) {
66bdbe82 23 return scalar @posts if @posts <= $aperture;
38efa3f1 24 my @next_post = splice(@posts, 0, $aperture);
66bdbe82 25 return 0 if day_diff(DateTime->now, $next_post[-1]) > $days;
38efa3f1 26 my $success = $aperture;
67e9aef2 27 foreach my $post (@posts) {
66bdbe82 28 if (day_diff($next_post[0],$post) > $days) {
29 return $success;
30 }
67e9aef2 31 $success++;
32 shift(@next_post);
33 push(@next_post, $post);
34 }
35 return $success;
36}
38efa3f1 37
a51e36e5 38sub check_time_remaining ($aperture, $days, @posts) {
39 my $cand = (@posts > $aperture ? $posts[$aperture - 1] : $posts[-1]);
66bdbe82 40 my $days_ago = day_diff(DateTime->now, $cand);
41 return $days - $days_ago;
a51e36e5 42}
43
a7b549f9 44sub check_both ($check, @posts) {
66bdbe82 45 return min(
a7b549f9 46 $check->(1, 10, @posts), # 10 days between posts
47 $check->(4, 32, @posts), # 4 posts within any given 32 days
38efa3f1 48 );
49}
ac04ccd9 50
a7b549f9 51sub successful_sequential_posts (@posts) {
52 return check_both(\&check_post_gap, @posts);
53}
54
38827ef4 55sub days_remaining_to_post (@posts) {
a7b549f9 56 return check_both(\&check_time_remaining, @posts);
57}
58
ac04ccd9 591;