Hi I am developing an app using Kotlin that displays the operating hours of a mini mart. I am currently trying to reformat a given string of operating time of a mini mart so that I can display it in a string based on the mini mart's daily operating hours (I am reading from an API). The strings I am given are for example,
val string1 = "Mon-Thu, Sun 11:30 am - 9:00 pm / Fri-Sat 11:30 am - 9:30 pm"
val string2 = "Mon-Sun 11:00 am - 10:30 pm"
val string3 = "Mon-Thu, Sun 11:30 am - 10:00 pm / Fri-Sat 11:30 am - 10:30 pm"
and I want to make them into a single string like
Mon 11:30 am - 9:00 pm
Tue 11:30 am - 9:00 pm
Wed 11:30 am - 9:00 pm
Thu 11:30 am - 9:00 pm
Fri 11:30 am - 9:30 pm
Sat 11:30 am - 9:30 pm
Sun 11:30 am - 9:00 pm
I appreciate your time to look into my problem.
CodePudding user response:
This function first creates a list of periods containing all possible combinations, like Mon-Tue, Mon-Wed, Mon-Thu, ..., Fri-Sat, Fri-Sun, Sat-Sun. The seven days are then appended to that list.
The main code works like this for this initial string:
Mon-Thu, Sun 11:30 am - 9:30 pm / Fri-Sat 11:30 am - 9:30 pm
Split string by "/"
Mon-Thu, Sun 11:30 am - 9:30 pm
Fri-Sat 11:30 am - 9:30 pmFor each item split by the first digit found (and trim)
parts[0]: Mon-Thu, Sun
parts[1]: 11:30 am - 9:30 pmFor each parts[0] split by comma to get the periods (and trim)
Mon-Thu
SunFor each period filter periods and return the list with all days of that period
[ Mon, Tue, Wed, Thu ]
Return pairs with the index of the day within the week and the output string
1 to "Mon 11:30 am - 9:30 pm"
2 to "Tue 11:30 am - 9:30 pm"
3 to "Wed 11:30 am - 9:30 pm"
4 to "Thu 11:30 am - 9:30 pm"Sort the result list by the index of the day within the week
Return the list joined by newlines
_
fun convert(s: String): String {
val days = listOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
val periods = days
.flatMap { from ->
days
.subList(days.indexOf(from) 1, days.count())
.map { till -> "$from-$till" to days.subList(days.indexOf(from), days.indexOf(till) 1) }
} days.map { it to listOf(it) }
return s
.split("/")
.flatMap {
val parts = it.split("(?=\\d)".toRegex(), 2).map { s -> s.trim() }
parts[0]
.split(",")
.map { period -> period.trim() }
.flatMap { period ->
periods
.first { p -> p.first == period }
.second
.map { day -> days.indexOf(day) to "$day ${parts[1]}" }
}
}
.sortedBy { it.first }
.joinToString("\n") { it.second }
}
val string1 = "Mon-Thu, Sun 11:30 am - 9:30 pm / Fri-Sat 11:30 am - 9:30 pm"
val string2 = "Mon-Sun 11:00 am - 10:30 pm"
val string3 = "Mon-Thu, Sun 11:30 am - 10:00 pm / Fri-Sat 11:30 am - 10:30 pm"
val string4 = "Wed 9:30 am - 9:30 pm / Thu 10:00 am - 7:30 pm / Fri-Sat 11:30 am - 10:30 pm"
val string5 = "Fri 12:30 am - 7:30 pm"
println(convert(string1) "\n")
println(convert(string2) "\n")
println(convert(string3) "\n")
println(convert(string4) "\n")
println(convert(string5) "\n")