2014-06-23 22:47:28 -07:00
|
|
|
package DDG::GoodieRole::NumberStyler;
|
|
|
|
|
|
|
|
use strict;
|
|
|
|
use warnings;
|
|
|
|
|
|
|
|
use Moo::Role;
|
|
|
|
use DDG::GoodieRole::NumberStyle;
|
|
|
|
|
|
|
|
use List::Util qw( all first );
|
|
|
|
|
|
|
|
# If it could fit more than one the first in order gets preference.
|
|
|
|
my @known_styles = (
|
|
|
|
DDG::GoodieRole::NumberStyle->new({
|
2014-07-27 05:49:32 -07:00
|
|
|
id => 'perl',
|
|
|
|
decimal => '.',
|
|
|
|
thousands => ',',
|
|
|
|
exponential => 'e',
|
2014-06-23 22:47:28 -07:00
|
|
|
}
|
|
|
|
),
|
|
|
|
DDG::GoodieRole::NumberStyle->new({
|
2014-07-27 05:49:32 -07:00
|
|
|
id => 'euro',
|
|
|
|
decimal => ',',
|
|
|
|
thousands => '.',
|
|
|
|
exponential => 'e',
|
2014-06-23 22:47:28 -07:00
|
|
|
}
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
sub number_style_regex {
|
2014-07-30 14:09:36 -07:00
|
|
|
my $return_regex = join '|', map { $_->number_regex } @known_styles;
|
|
|
|
return qr/$return_regex/;
|
2014-06-23 22:47:28 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
# Takes an array of numbers and returns which style to use for parse and display
|
|
|
|
# If there are conflicting answers among the array, will return undef.
|
|
|
|
sub number_style_for {
|
|
|
|
my @numbers = @_;
|
|
|
|
|
|
|
|
my $style; # By default, assume we don't understand the numbers.
|
|
|
|
|
|
|
|
STYLE:
|
|
|
|
foreach my $test_style (@known_styles) {
|
2014-07-27 05:49:32 -07:00
|
|
|
my $exponential = lc $test_style->exponential; # Allow for arbitrary casing.
|
|
|
|
if (all { $test_style->understands($_) } map { split /$exponential/, lc $_ } @numbers) {
|
2014-06-23 22:47:28 -07:00
|
|
|
# All of our numbers fit this style. Since we have them in preference order
|
|
|
|
# we can pick it and move on.
|
|
|
|
$style = $test_style;
|
|
|
|
last STYLE;
|
|
|
|
}
|
|
|
|
}
|
2014-07-27 19:05:05 -07:00
|
|
|
|
2014-06-23 22:47:28 -07:00
|
|
|
return $style;
|
|
|
|
}
|
|
|
|
|
|
|
|
1;
|