Skip to content

Instantly share code, notes, and snippets.

@ulrikdamm
Last active October 27, 2016 11:18
Show Gist options
  • Save ulrikdamm/2e2795e7d8a01258937b8d678ee9b9aa to your computer and use it in GitHub Desktop.
Save ulrikdamm/2e2795e7d8a01258937b8d678ee9b9aa to your computer and use it in GitHub Desktop.
enum Block {
case code(String)
case text(String)
case header(String)
}
enum PlaygroundElement {
case code(String)
case documentation([Block])
}
func playground(blocks : [Block]) -> [PlaygroundElement] {
return blocks.reduce([], appendBlock)
}
func appendBlock(to elements : [PlaygroundElement], block : Block) -> [PlaygroundElement] {
switch block {
case .code(let code): return elements + [.code(code)]
case .text(let text): return updateDocumentation(result: elements, newBlock: .text(text))
case .header(let header): return updateDocumentation(result: elements, newBlock: .header(header))
}
}
func updateDocumentation(result : [PlaygroundElement], newBlock : Block) -> [PlaygroundElement] {
if case .documentation(let blocks)? = result.last {
let updatedDocumentation = PlaygroundElement.documentation(blocks + [newBlock])
return Array(result.dropLast()) + [updatedDocumentation]
} else {
return result + [.documentation([newBlock])]
}
}
let sample : [Block] = [.code("swift sample code"), .header("My Header"), .text("Hello"), .code("more"), .text("text")]
let result: [PlaygroundElement] = [
.code("swift sample code"),
.documentation([Block.header("My Header"), .text("Hello")]),
.code("more"),
.documentation([.text("text")])
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment