Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
XCTest to look at tail-call optimization
import XCTest
class FlattenTests: XCTestCase {
var input: [Any] = []
override func setUp() {
let test: [Any] = [1, [2], [3, [4]], [5, [6]], 7, [8], [[[[9, [10]]], [11, [12], 13]], 14, [15, [16]], [17, [18]], 19], 20, [21, 22], [23, 24, 25]]
let level1 = [test, test, test, test, test]
let level2 = [level1, level1, level1, level1]
let level3 = [level2, level2, level2, level2]
let level4 = [level3, level3, level3, level3]
input = [level4, level4, level4, level4]
}
func testFlatten() {
self.measure {
let _ = flatten1(input: self.input)
}
}
func testFlatten2() {
self.measure {
let _ = flatten2(input: self.input)
}
}
func testFlatten3() {
self.measure {
let _ = flatten3(input: self.input)
}
}
func testFlatMap() {
self.measure {
let _ = self.input.flatMap{ $0 }
}
}
}
func flatten1(input: [Any]) -> [Any] {
var flattened = [Any] ()
for index in 0..<input.count {
let element = input[index]
if let array = element as? [Any] {
flattened.append(contentsOf: flatten1(input: array))
}
else {
flattened.append(element)
}
}
return flattened
}
func flatten2(input: [Any]) -> [Any] {
guard let head = input.first else { return [] }
if let headArray = head as? [Any] {
return flatten2(input: headArray) + flatten2(input: Array(input.dropFirst()))
}
else {
return [head] + flatten2(input: Array(input.dropFirst()))
}
}
func flatten3(input: [Any], accumulated: [Any] = []) -> [Any] {
guard let head = input.first else { return accumulated }
if let headArray = head as? [Any] {
return
flatten3(input: Array(input.dropFirst()),
accumulated: flatten3(input: headArray, accumulated:accumulated))
}
else {
var _accumulated = accumulated
_accumulated.append(head)
return flatten3(input: Array(input.dropFirst()),
accumulated: _accumulated)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.