我通过做一些练习来学习打字稿,我试图从exercism.io的打字稿轨中实现时钟。
我的时钟应该能够添加和减去分钟,而且我应该处理负值
这是我尝试过的
export default class Clock {
hours: number
min: number
constructor( hours: number, min: number = 0) {
this.hours = hours
this.min = min
this.format()
}
format() {
let removedHours:number , addedHours :number
if(this.min < 0){
removedHours = Math.floor(Math.abs(this.min ) / 60) +1
this.hours -= removedHours
}
if(this.min >= 0){
addedHours = Math.floor(Math.abs(this.min ) / 60)
this.hours += addedHours
}
this.min = this.min % 60
this.hours = this.hours % 24
}
minus(min: number) {
this.min -= min
this.format()
return this
}
plus(min: number) {
this.min += min
this.format()
return this
}
equals(clock: Clock) {
return clock.hours == this.hours && clock.min == this.min
}
toString() {
return this.pad(this.hours) + ':' + this.pad(this.min)
}
pad(num: number, size: number = 2) {
var s = "000000000" + num;
return s.substr(s.length - size);
}
}
如您所见,我的想法是使愚蠢的内容相减,然后格式化从分钟开始的值
我要检查50个单元测试才能提交
问题是我觉得我的取模不正常
-1模24的结果应为23
但是根据我的测试,-1保持不变
测试如下
test('subtract across midnight', () => {
expect(new Clock(0, 3).minus(4).toString()).toEqual('23:59')
})