1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use Test::More;
7
8use List::UtilsBy qw(
9   max_by nmax_by
10   min_by nmin_by
11   minmax_by nminmax_by
12);
13
14# max_by
15{
16   is_deeply( [ max_by {} ], [], 'empty list yields empty' );
17
18   is_deeply( ( scalar max_by { $_ } 10 ), 10, 'unit list yields value in scalar context' );
19   is_deeply( [ max_by { $_ } 10 ], [ 10 ], 'unit list yields unit list value' );
20
21   is_deeply( ( scalar max_by { $_ } 10, 20 ), 20, 'identity function on $_' );
22   is_deeply( ( scalar max_by { $_[0] } 10, 20 ), 20, 'identity function on $_[0]' );
23
24   is_deeply( ( scalar max_by { length $_ } "a", "ccc", "bb" ), "ccc", 'length function' );
25
26   is_deeply( ( scalar max_by { length $_ } "a", "ccc", "bb", "ddd" ), "ccc", 'ties yield first in scalar context' );
27   is_deeply( [ max_by { length $_ } "a", "ccc", "bb", "ddd" ], [ "ccc", "ddd" ], 'ties yield all maximal in list context' );
28
29   is_deeply( ( scalar nmax_by { $_ } 10, 20 ), 20, 'nmax_by alias' );
30}
31
32# min_by
33{
34   is_deeply( [ min_by {} ], [], 'empty list yields empty' );
35
36   is_deeply( ( scalar min_by { $_ } 10 ), 10, 'unit list yields value in scalar context' );
37   is_deeply( [ min_by { $_ } 10 ], [ 10 ], 'unit list yields unit list value' );
38
39   is_deeply( ( scalar min_by { $_ } 10, 20 ), 10, 'identity function on $_' );
40   is_deeply( ( scalar min_by { $_[0] } 10, 20 ), 10, 'identity function on $_[0]' );
41
42   is_deeply( ( scalar min_by { length $_ } "a", "ccc", "bb" ), "a", 'length function' );
43
44   is_deeply( ( scalar min_by { length $_ } "a", "ccc", "bb", "e" ), "a", 'ties yield first in scalar context' );
45   is_deeply( [ min_by { length $_ } "a", "ccc", "bb", "ddd", "e" ], [ "a", "e" ], 'ties yield all minimal in list context' );
46
47   is_deeply( ( scalar nmin_by { $_ } 10, 20 ), 10, 'nmin_by alias' );
48}
49
50# minmax_by
51{
52   is_deeply( [ minmax_by {} ], [], 'empty list yields empty' );
53
54   is_deeply( [ minmax_by { $_ } 10 ], [ 10, 10, ], 'unit list yields value twice' );
55
56   is_deeply( [ minmax_by { $_ } 10, 20, 30, 40, 50 ], [ 10, 50 ], 'identity function on $_' );
57   is_deeply( [ minmax_by { $_[0] } 10, 20, 30, 40, 50 ], [ 10, 50 ], 'identity function on $_[0]' );
58
59   is_deeply( [ minmax_by { $_ } 50, 40, 30, 20, 10 ], [ 10, 50 ], 'identity function on reversed input' );
60
61   is_deeply( [ minmax_by { length $_ } "a", "ccc", "bb" ], [ "a", "ccc" ], 'length function' );
62
63   is_deeply( [ nminmax_by { $_ } 10 ], [ 10, 10, ], 'nminmax_by alias' );
64}
65
66done_testing;
67