#!/usr/bin/env perl

use Test::More tests => 9;

use strict;
use warnings;

use List;

# Bad arg testing
eval { first(); };
like( $@, qr/^First argument is not/, 'Generates an error if no args' );
eval { first( qw/a b c d e f g h/ ); };
like( $@, qr/^First argument is not/, 'Generates an error if no predicate arg' );

# Happy path
is( first( sub { $_ == 3 }, ( 1 .. 5 ) ), 3, 'Matches a specific value' );
ok( !defined first( sub { $_ == 7 }, ( 1 .. 5 ) ), 'Returns undef if not found' );

# predicate testing
my @test_data = (
    { 'name' => 'David Shenk', 'gender' => 'M', 'userid' => 'electrode', 'nom' => 'Electrode' },
    { 'name' => 'Kristen Austin', 'gender' => 'F', 'userid' => 'clemsongirl', },
    { 'name' => 'Mark Dagon', 'gender' => 'M', 'userid' => 'moranderin', },
    { 'name' => 'Connie Ronin', 'gender' => 'F', 'userid' => 'fencer1', },
);

is_deeply( first( sub { $_->{gender} eq 'F' }, @test_data ), $test_data[1], 'Found second item' );
is_deeply( first( sub { $_->{name} =~ /Connie/ }, @test_data ), $test_data[3], 'Found last item' );
is_deeply( first( sub { defined $_->{nom} }, @test_data ), $test_data[0], 'Found first item' );

my @names = map { $_->{name} } @test_data;

is( first( qr/Da/, @names ), 'David Shenk', 'Simple regex match' );
is( first( qr/(\w)\1/, @names ), 'Connie Ronin', 'Slightly more complicated match' );