BoardStreams/Util.pm untested

filter: Statementstmt 0.0% 0 / 69 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 115 CC 3 SCAR 9.9
CC
3
Cov
0%
eqq
6.0
hashify
6.0
make_one_line
2.0
CRAP 2.7
1 package BoardStreams::Util;
2  
3 use Mojo::Base -strict, -signatures, -async_await;
4  
5 use Mojo::Promise;
6 use Mojo::IOLoop;
7 use Mojo::JSON qw/ true false from_json to_json /;
8 use Syntax::Keyword::Try;
9 use Text::Trim 'trim';
10 use Data::GUID::URLSafe;
11 use List::AllUtils 'any';
12 use Encode::Simple qw/ encode_utf8 decode_utf8 /;
13 use Carp 'croak';
14 use Scalar::Util 'refaddr';
15  
16 use Exporter 'import';
17 our @EXPORT_OK = qw/
18 make_one_line eqq belongs_to trim true false
19 unique_id hashify next_tick_p sleep_p
20 encode_json decode_json
21 /;
22 our %EXPORT_TAGS = (bool => [qw/ true false /]);
23  
24 our $VERSION = "v0.0.36";
25  
26 sub make_one_line :prototype(_) ($text) {
27 return trim(
28 $text =~ s/^\s+/ /mgr
29 );
30 }
31  
32 sub eqq ($x, $y) {
33 defined $x or return !defined $y;
34 defined $y or return !!0;
35 ref $x eq ref $y or return !!0;
36 return length(ref $x) ? refaddr($x) == refaddr($y) : $x eq $y;
37 }
38  
39 sub belongs_to ($x, $array) {
40 return any { eqq($_, $x) } @$array;
41 }
42  
43 sub unique_id { Data::GUID->new->as_base64_urlsafe }
44  
45 sub hashify ($hashes, $fields, $sub = undef) {
46 my $ret = {};
47  
48 foreach my $hash (@$hashes) {
49 my $cursor = \$ret;
50 foreach my $field (@$fields) {
51 my $value = $hash->{$field};
52 $cursor = \($$cursor->{$value} //= {});
53 }
54 $$cursor = $sub ? do {
55 local $_ = $hash;
56 $sub->($hash);
57 } : $hash;
58 }
59  
60 return $ret;
61 }
62  
63 sub next_tick_p {
64 my $p = Mojo::Promise->new;
65  
66 Mojo::IOLoop->next_tick(sub {
67 $p->resolve();
68 });
69  
70 return $p;
71 }
72  
73 sub sleep_p :prototype(_) ($duration) {
74 my $p = Mojo::Promise->new;
75  
76 Mojo::IOLoop->timer($duration, sub {
77 $p->resolve();
78 });
79  
80 return $p;
81 }
82  
83 sub encode_json :prototype(_) ($data) { encode_utf8 to_json $data }
84  
85 sub decode_json :prototype(_) ($bytes) { from_json decode_utf8 $bytes }
86  
87 1;