Last active
October 27, 2016 11:18
-
-
Save ulrikdamm/2e2795e7d8a01258937b8d678ee9b9aa to your computer and use it in GitHub Desktop.
Playground Generator (my solution to https://gist.github.com/chriseidhof/b0fb6b0a4cf370e873dc56ee0a6ad42d)
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
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