Algorithm-BestChoice

 view release on metacpan or  search on metacpan

lib/Algorithm/BestChoice.pm  view on Meta::CPAN


# TODO: Document ->best() ->best( [ ... ] )

use Moose;

use Algorithm::BestChoice::Matcher;
use Algorithm::BestChoice::Ranker;
use Algorithm::BestChoice::Result;
use Algorithm::BestChoice::Option;

use Scalar::Util qw/looks_like_number/;

has options => qw/is ro required 1 isa ArrayRef/, default => sub { [] };

sub add {
    my $self = shift;
    my %given = @_;

    $given{matcher} = $given{match} unless exists $given{matcher};
    $given{ranker} = $given{rank} unless exists $given{ranker};
    my ($matcher, $ranker) = @given{ qw/matcher ranker/ };

lib/Algorithm/BestChoice.pm  view on Meta::CPAN

    my $self = shift;
    my $key = shift;

    my @tally;
    for my $option (@{ $self->options }) {
        if (my $match = $option->match( $key )) {
            my $rank;
            if (ref $match eq 'HASH') {
                $rank = $match->{rank};
                die "Got an undefined rank from a match" unless defined $rank;
                die "Got a non-numeric rank ($rank) from a match" unless looks_like_number $rank;
            }
            else {
                $rank = $option->rank( $key );
                die "Got an undefined rank from a ranker" unless defined $rank;
                die "Got a non-numeric rank ($rank) from a ranker" unless looks_like_number $rank;
            }
            push @tally, Algorithm::BestChoice::Result->new( rank => $rank, value => $option->value );
        }
    }

    return @tally;
}

# TODO: Test for this multi-key ranker
# TODO: Probably want to give different weights to different keys!

lib/Algorithm/BestChoice/Ranker.pm  view on Meta::CPAN

package Algorithm::BestChoice::Ranker;

use Moose;

use Scalar::Util qw/looks_like_number/;

sub parse {
    my $class = shift;
    my $ranker = shift;

    return Algorithm::BestChoice::Ranker::Value->new( value => 0 ) unless defined $ranker;

    if (ref $ranker eq '' && looks_like_number $ranker) {
        return Algorithm::BestChoice::Ranker::Value->new( value => $ranker );
    }
    elsif (ref $ranker eq 'CODE') {
        return Algorithm::BestChoice::Ranker::Code->new( code => $ranker );
    }

    die "Don't understand ranker $ranker";
}

sub rank {



( run in 0.381 second using v1.01-cache-2.11-cpan-64827b87656 )