Skip to content

Commit

Permalink
calendar.format: make duration>human-readable more human readable
Browse files Browse the repository at this point in the history
  • Loading branch information
mrjbq7 committed May 2, 2024
1 parent 37103d3 commit 7cc710a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
7 changes: 7 additions & 0 deletions basis/calendar/format/format-tests.factor
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,10 @@ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
{ "about a minute ago" } [ 60 relative-time ] unit-test
{ "about a minute ago" } [ 90 relative-time ] unit-test
{ "4 minutes ago" } [ 270 relative-time ] unit-test

{ "1 minute" } [ 60 seconds duration>human-readable ] unit-test
{ "1 hour" } [ 1 hours duration>human-readable ] unit-test
{ "3 hours" } [ 3 hours duration>human-readable ] unit-test
{ "2 minutes and 3 seconds" } [ 123 seconds duration>human-readable ] unit-test
{ "20 minutes and 34 seconds" } [ 1234 seconds duration>human-readable ] unit-test
{ "3 hours, 25 minutes and 45 seconds" } [ 12345 seconds duration>human-readable ] unit-test
49 changes: 36 additions & 13 deletions basis/calendar/format/format.factor
Original file line number Diff line number Diff line change
Expand Up @@ -205,20 +205,43 @@ M: timestamp present timestamp>string ;

: duration>human-readable ( duration -- string )
[
[
duration>years >integer
[
[ number>string write ]
[ 1 > " years, " " year, " ? write ] bi
] unless-zero
] [
duration>days >integer 365 mod
{
[
[ number>string write ]
[ 1 > " days, " " day, " ? write ] bi
] unless-zero
] [ duration>hms write ] tri
] with-string-writer ;
duration>years >integer
[
[ number>string ]
[ 1 > " years" " year" ? append , ] bi
] unless-zero
] [
duration>days >integer 365 mod
[
[ number>string ]
[ 1 > " days" " day" ? append , ] bi
] unless-zero
] [
duration>hours >integer 24 mod
[
[ number>string ]
[ 1 > " hours" " hour" ? append , ] bi
] unless-zero
] [
duration>minutes >integer 60 mod
[
[ number>string ]
[ 1 > " minutes" " minute" ? append , ] bi
] unless-zero
] [
duration>seconds >integer 60 mod
[
number>string " seconds" append ,
] unless-zero
]
} cleave
] { } make [ "0 seconds" ] [
unclip-last-slice over empty? [ nip ] [
[ ", " join ] [ " and " glue ] bi*
] if
] if-empty ;

GENERIC: elapsed-time ( seconds -- string )

Expand Down

0 comments on commit 7cc710a

Please sign in to comment.