Skip to content

Instantly share code, notes, and snippets.

@vikingosegundo
Last active October 19, 2021 12:54
Show Gist options
  • Save vikingosegundo/00184fbde3c8da048fd0e6f6ff385535 to your computer and use it in GitHub Desktop.
Save vikingosegundo/00184fbde3c8da048fd0e6f6ff385535 to your computer and use it in GitHub Desktop.
public func change(_ state: AppState, _ change: [ AppState.Change ] ) -> AppState { state.alter(change) }
public struct AppState: Codable {
public enum Change: Equatable {
case by(_By); public enum _By: Equatable {
case adding(_Add); public enum _Add: Equatable {
case light(Light) }
case replacing(_Replace); public enum _Replace: Equatable {
case lights(with:[Light])
case light (with:Light )
case rooms (with:[Room] )
}
}
}
public func alter(_ changes: [ Change ] ) -> AppState { changes.reduce(self) { $0.alter($1) } }
private func alter (_ change:Change) -> Self {
func sort (_ lights:[Light]) -> [Light] { lights.sorted(on:\.id, by:<) }
func remove(_ light: Light, from lights:[Light]) -> [Light] { lights.filter{$0.id != light.id} }
switch change {
case let .by(.adding (.light (light ))): return .init(sort(lights + [light]), rooms)
case let .by(.replacing(.lights(lights))): return .init( lights , rooms)
case let .by(.replacing(.light (light ))): return .init(sort(remove(light, from:lights) + [light]), rooms)
case let .by(.replacing(.rooms (rooms ))): return .init( lights , rooms)
}
}
public init() {
self.lights = []
self.rooms = []
}
init(_ lights: [Light],_ rooms: [Room]) {
self.lights = lights
self.rooms = rooms
}
public let lights: [Light]
public let rooms : [Room ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment