我在一次面试中问到了这个问题,在最后一节我和科特林乐队的谈话中失败了。我正在尝试重新创建fun taskCompleted() --我想看看如何实现它,仅仅是为了玩它。所以这就是我所得到的
data class Article(val title: String, val content: String, val duration: Int, val date: Int)
data class StreakInfo(val goalsMet: Int, val breakDown: List<Boolean>)
interface ReadingGoalService{
fun getDailyReadingGoal(): Int
}
interface TaskService{
fun allTasks(): List<Article>
}
class MockInterview{
fun taskCompleted(){}
//temporary
private fun today(): Int{
return 1
}
}
fun getAllSteaks(streakInfo: StreakInfo){
//don't implement
}我的要求是在哪里做fun taskCompleted(),我应该做以下几件事
//TODO 1 current day is today
//TODO 2 take all the articles that were read on the current day
//TODO 3 sum readingDurations of articles for current Day
//TODO 4 check if sum of readingDurations is >= than reading goal
// TODO 5 if sum of readingDuration is >= goal repeat 2..3.. and 4. for currentDay-1
//TODO 6 if sum of readingDuration is < goal - stop知道我怎么能在科特林做到这一点吗?我计划将此作为一个学习过程。
发布于 2022-01-18 22:09:06
正如我所提到的,我强烈建议您看看Kotlin Koans,因为他们向您介绍了许多我认为肯定会教您如何执行几乎所有那些TODO的例子!(他们有解决办法!)
在这次采访中,您是否知道如何使用Kotlin标准库中的聚合和映射函数,并检查是否可以通过使用适当数量的参数来重用大量代码。
以下是我如何处理这个问题:
fun today() = 1 // TODO 1: Current day is today
fun tasksDoneByDay(taskService: TaskService, day: Int = today()): List<Article> {
// TODO2: Here I have all tasks that were done at "today()"
return taskService.allTasks().filter { task -> task.date == day }
}
// TODO 3
fun durationsForDay(taskService: TaskService, day: Int = today()) = tasksDoneByDay(taskService, day).sumBy { it.duration }
// TODO 4
fun durationsForDayMeetGoal(taskService: TaskService, goal: Int, day: Int = today()) = durationsForDay(taskService, day) >= goal
// TODO 5 if sum of readingDuration is >= goal repeat 2..3.. and 4. for currentDay-1
fun todo5(taskService: TaskService, goal: Int) {
val today = today()
return when(val durationsForTodayMeetGoal = durationsForDayMeetGoal(taskService, goal, today)) {
false -> durationsForDayMeetGoal(taskService, goal, today - 1)
true -> durationsForTodayMeetGoal
}
}
// TODO 6 I don't understand...
essentially the same as todo five but when it's false dont do anything?https://stackoverflow.com/questions/70762855
复制相似问题