softnshare / kata

Code Kata 這個概念是由 The Pragmatic Programmer 的作者之一Dave Thomas提出的, 想要提升自己的coding skill嗎? 歡迎加入這個slack channel, 加入請參考右邊網頁說明
https://softnshare.wordpress.com/slack/kata/
38 stars 4 forks source link

Human readable duration format #19

Open houjunchen opened 8 years ago

houjunchen commented 8 years ago

Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.

The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds.

It is much easier to understand with an example:

format_duration(62)    # returns "1 minute and 2 seconds"
format_duration(3662)  # returns "1 hour, 1 minute and 2 seconds"

Note that spaces are important.

The resulting expression is made of components like 4 seconds, 1 year, etc. In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1.

The components are separated by a comma and a space (", "). Except the last component, which is separated by " and ", just like it would be written in English.

A more significant units of time will occur before than a least significant one. Therefore, 1 second and 1 year is not correct, but 1 year and 1 second is.

Different components have different unit of times. So there is not repeated units like in 5 seconds and 1 second.

A component will not appear at all if its value happens to be zero. Hence, 1 minute and 0 seconds is not valid, but it should be just 1 minute.

A unit of time must be used "as much as possible". It means that the function should not return 61 seconds, but 1 minute and 1 second instead. Formally, the duration specified by of a component must not be greater than any valid more significant unit of time.

For the purpose of this Kata, a year is 365 days and a day is 24 hours.


這個題目的目的是要將輸入的秒數轉成人類可讀的格式。輸入的參數為一非負整數,若為0,則回傳 "now",否則回傳yearsdayshoursminutesseconds 的組合。

以下為例:

format_duration(62)    # returns "1 minute and 2 seconds"
format_duration(3662)  # returns "1 hour, 1 minute and 2 seconds"

要注意空白的位置。

也要注意時間單位的單複數,時間值如果大於1,單位要用複數。單位與單位之間要用逗號與空格隔開( ", "),除了最後一個間隔要用 " and ",就跟平常英文慣用的格式一樣。

時間單位不能重複,也就是不會有 5 seconds and 1 second 這樣的狀況出現。如果時間值為0的話,該單位就不顯示,像是 1 minute and 0 seconds1 minute 就好。時間的表示要「越多單位越好」,也就是 61 seconds 應該用 1 minute and 1 second 表示。

假設一年有365天,一天有24小時。

https://www.codewars.com/kata/human-readable-duration-format

houjunchen commented 8 years ago

Pass

bucker commented 8 years ago

Pass, 沒 Java 捏,你應該是看到 CoffeeScript 了

vampireneo commented 8 years ago

Pass