Skip to content

Commit

Permalink
Make Date/DateTime.yyyy-mm-dd about 250x as fast
Browse files Browse the repository at this point in the history
Also allow a separator to be specified, so that you can now say:

    Date.yyyy-mm-dd("/") to get "2020/03/14" for today.

The default separator being "-", to remain compatible with earlier
versions.

It dawned upon me that:
 a. .yyyy-mm-dd was basically the default formatter of Date
 b. adding an optional separator would have close to no performance effects
  • Loading branch information
lizmat committed Mar 14, 2020
1 parent af59492 commit 3017cfe
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
17 changes: 1 addition & 16 deletions src/core.c/Date.pm6
@@ -1,21 +1,6 @@
my class Date does Dateish {

method !formatter(--> Str:D) {
my $parts := nqp::list_s;
nqp::push_s($parts, $!year < 1000 || $!year > 9999
?? self!year-Str
!! nqp::tostr_I($!year)
);
nqp::push_s($parts, $!month < 10
?? nqp::concat('0',nqp::tostr_I($!month))
!! nqp::tostr_I($!month)
);
nqp::push_s($parts, $!day < 10
?? nqp::concat('0',nqp::tostr_I($!day))
!! nqp::tostr_I($!day)
);
nqp::join('-',$parts)
}
method !formatter(--> Str:D) { self.yyyy-mm-dd }

#?if moar
my constant $valid-units = nqp::hash(
Expand Down
17 changes: 15 additions & 2 deletions src/core.c/Dateish.pm6
Expand Up @@ -132,8 +132,21 @@ my role Dateish {
+ ($!month > 2 && IS-LEAP-YEAR($!year));
}

method yyyy-mm-dd(--> Str:D) {
sprintf '%04d-%02d-%02d',$!year,$!month,$!day
method yyyy-mm-dd(str $sep = "-" --> Str:D) {
my $parts := nqp::list_s;
nqp::push_s($parts, $!year < 1000 || $!year > 9999
?? self!year-Str
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!year'))
);
nqp::push_s($parts, $!month < 10
?? nqp::concat('0',$!month)
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!month'))
);
nqp::push_s($parts, $!day < 10
?? nqp::concat('0',$!day)
!! nqp::tostr_I(nqp::getattr_i(self,$?CLASS,'$!day'))
);
nqp::join($sep,$parts)
}

method earlier(*%unit) { self.later(:earlier, |%unit) }
Expand Down

0 comments on commit 3017cfe

Please sign in to comment.