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
|
|
|
}
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
2014-07-27 18:24:40 -07:00
|
|
|
# Be sure to update the below, as well, if new styles are added.
|
|
|
|
my $perl_match = $known_styles[0]->number_regex;
|
|
|
|
my $euro_match = $known_styles[1]->number_regex;
|
2014-06-23 22:47:28 -07:00
|
|
|
|
|
|
|
sub number_style_regex {
|
2014-07-27 18:24:40 -07:00
|
|
|
return qr/$perl_match|$euro_match/;
|
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;
|