Skip to content

Instantly share code, notes, and snippets.

@vikingosegundo
Created March 25, 2022 13:00
Show Gist options
  • Save vikingosegundo/930eb8748e35503ca1495f43e60730eb to your computer and use it in GitHub Desktop.
Save vikingosegundo/930eb8748e35503ca1495f43e60730eb to your computer and use it in GitHub Desktop.
func createStack<T>(with array:[T] = [], divider: (top: String, bottom: String) = (top:"-", bottom:"+")) -> _Stack<T> {
var array:[T] = array
var typeDescription: String { String(describing:T.self) }
var topDivider : String {
array.count > 0
? "\(3*divider.top) " + "Stack<\(typeDescription)>: \(array.count) elements " + "\(3*divider.top)" + "\n"
: "\(3*divider.top) " + "Empty Stack<\(typeDescription)> " + "\(3*divider.top)" + "\n"
}
var bottomDivider : String { divider.bottom * max((topDivider.count - 1), 0) + "\n" }
return (
push: { array.append($0) },
pop: { array.count > 0 ? array.remove(at:array.count - 1) : nil },
peek: { array.last },
string: { topDivider + array.reversed().reduce("") { $0 + String(reflecting:$1) + "\n" } + bottomDivider }
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment