« Coerce/js/To_bool/From_str/common_words.pm
↑ Summary
Coerce/js/To_datenotime/From_float/epoch.pm »
| 1 | package Data::Sah::Coerce::js::To_duration::From_str::iso8601; | ||
| 2 | |||
| 3 | 3 | ▶ | use 5.010001; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 3 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 3 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | |||
| 7 | 3 | our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY | |
| 8 | 3 | our $DATE = '2023-10-24'; # DATE | |
| 9 | 3 | our $DIST = 'Data-Sah-Coerce'; # DIST | |
| 10 | 3 | our $VERSION = '0.054'; # VERSION | |
| 11 | |||
| 12 | 2 | ▶ | sub meta { |
|
Subroutine
meta: called CC=1 SCAR=0.0
Pod
undocumented
| |||
| 13 | +{ | ||
| 14 | 2 | v => 4, | |
| 15 | summary => 'Coerce duration from (subset of) ISO8601 string (e.g. "P1Y2M", "P14M")', | ||
| 16 | prio => 50, | ||
| 17 | }; | ||
| 18 | } | ||
| 19 | |||
| 20 | 2 | ▶ | sub coerce { |
|
Subroutine
coerce: called CC=1 SCAR=0.0
Pod
undocumented
| |||
| 21 | 2 | my %args = @_; | |
| 22 | |||
| 23 | 2 | my $dt = $args{data_term}; | |
| 24 | 2 | my $coerce_to = $args{coerce_to}; | |
| 25 | |||
| 26 | 2 | my $res = {}; | |
| 27 | |||
| 28 | 2 | my $re_num = '[0-9]+(?:\\.[0-9]+)?'; | |
| 29 | # js doesn't support /x flag, nor \A and \z. oh my | ||
| 30 | # #1=Y #2=M(on) #3=W #4=D #5=H #6=M(in) #7=S | ||
| 31 | 2 | my $expr_re_match = "$dt.match(/^P(?:($re_num)Y)?(?:($re_num)M)?(?:($re_num)W)?(?:($re_num)D)?(?:T(?:($re_num)H)?(?:($re_num)M)?(?:($re_num)S)?)?\$/)"; | |
| 32 | 2 | $res->{expr_match} = join( | |
| 33 | " && ", | ||
| 34 | "typeof($dt)=='string'", | ||
| 35 | $expr_re_match, | ||
| 36 | ); | ||
| 37 | |||
| 38 | # XXX i need a trick to avoid doing regex match twice | ||
| 39 | |||
| 40 | # approximation | ||
| 41 | 2 | $res->{expr_coerce} = "(function(_m) { _m = $expr_re_match; return ((_m[1]||0)*365.25*86400 + (_m[2]||0)*30.4375*86400 + (_m[3]||0)*7*86400 + (_m[4]||0)*86400 + (_m[5]||0)*3600 + (_m[6]||0)*60 + (_m[7]||0)*1) })()"; | |
| 42 | |||
| 43 | 2 | $res; | |
| 44 | } | ||
| 45 | |||
| 46 | 3 | 1; | |
| 47 | # ABSTRACT: Coerce duration from (subset of) ISO8601 string (e.g. "P1Y2M", "P14M") | ||
| 48 | |||
| 49 | __END__ | ||