Last active
July 1, 2020 16:33
-
-
Save voxqhuy/6f5a0915b267ed1f5a677b5e4b9a0424 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Toaster | |
class Bread { | |
var cookedTime: Double = 0.0 | |
} | |
enum TrayLevel { | |
case down | |
case up | |
} | |
class Status { | |
var slots: (Bread?, Bread?) | |
var toastTime: Double | |
init(slots: (Bread?, Bread?), toastTime: Double) { | |
self.slots = slots | |
sell.toastTime = toastTime | |
} | |
} | |
protocol StatusDelegate { | |
func didUpdateStatus() | |
} | |
class Toaster { | |
var status: Status { | |
didSet { | |
statusDelegate.didUpdateStatus() | |
} | |
} | |
var statusDelegate: StatusDelegate? | |
var didEject: Bool | |
var toastLevel: Double | |
var tray: TrayLevel | |
init() { | |
status = Status(slots: (0, 0), toastTime: 0) | |
didEject = true | |
toastLevel = 0 | |
tray = .down | |
} | |
// assuming: | |
// 1. only add one slice at a time | |
// 2. the slots are indexed 0 and 1 | |
func addBread(_ bread: Bread, toSlot slot: String) { | |
if slots.0 != nil && slots.1 != nil { | |
print("Both slots are in use. Try again later") | |
return | |
} | |
if slot == 0 && slot.0 != nil { | |
print("Slot 0 is in use. Adding bread to slot 1...") | |
slots.1 = bread | |
} else if slot == 1 && slot.1 != nil { | |
print("Slot 1 is in use. Adding bread to slot 0...") | |
slots.0 = bread | |
} else { | |
slots.slot = bread | |
} | |
} | |
func changeLevel(level: Double) { | |
toastLevel = level | |
// if the tray is down, change level to 0 will force eject it | |
if tray == .down & level == 0 { | |
eject() | |
} | |
} | |
func run() { | |
if slots.0 == nil && slots.1 == nil { | |
print("Please add bread") | |
return | |
} | |
didEject = false | |
tray = .down | |
toast() | |
} | |
// recursive call | |
func toast() { | |
if didEject == false && toastLevel > 0 { | |
DispatchQueue.main.asyncAfter(deadline: now() + 0.5) { | |
// keep the heat up every 0.5 seconds, and turn the level down by 0.05 (1 level = 10 seconds) | |
if slots.0 != nil { slots.0.cookedTime = slots.0.cookedTime + 0.5 } | |
if slots.1 != nil { slots.1.cookedTime = slots.1.cookedTime + 0.5 } | |
toastLevel -= 0.05 | |
toast() | |
} | |
} else if toastLevel == 0 { | |
eject() | |
} | |
} | |
func takeBread(atSlot slot: Int) -> Bread? { | |
if slots.slot == nil { | |
print("The slot is empty") | |
return nil | |
} else { | |
let bread = slots.slot | |
// empty the slot | |
slots.slot = nil | |
return bread | |
} | |
} | |
func eject() -> (Bread?, Bread?) { | |
didEject = true | |
tray = .up | |
return status.slots | |
} | |
} | |
// ---------------------- ***** ---------------------- // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment