Skip to content

Commit

Permalink
Merge pull request #5 from 0xLeif/develop
Browse files Browse the repository at this point in the history
0.3.0 Flatten
  • Loading branch information
0xLeif authored Mar 2, 2021
2 parents 635c449 + f91b21c commit a4b2b0c
Showing 1 changed file with 41 additions and 11 deletions.
52 changes: 41 additions & 11 deletions Sources/E/Variable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,48 +21,78 @@ public extension Variable {
init() {
self = .void
}

init(bool: Bool) {
self = .bool(bool)
}

init(int: Int) {
self = .int(int)
}

init(float: Float) {
self = .float(float)
}

init(double: Double) {
self = .double(double)
}

init(string: String) {
self = .string(string)
}

init(set: Set<Variable>) {
self = .set(set)
}

init(array: [AnyHashable]) {
self = .array(array.map({ $0.variable }))
}

init(dictionary: [AnyHashable: AnyHashable]) {
let variable = Variable.dictionary([:])

if case .dictionary(var variable) = variable {
dictionary.forEach { (key, value) in
variable[value.variable] = value.variable
}
}

self = variable
}
}

public extension Variable {
var flatten: Variable {
guard case .array(let value) = self else {
return self
}

guard !value.isEmpty else {
return .array([])
}

guard value.count > 1 else {
return value[0]
}

let flattenedArray = value.map(\.flatten)

var flatArray = [Variable]()

for variable in flattenedArray {
if case .array(let values) = variable {
flatArray.append(contentsOf: values.map(\.flatten))
} else {
flatArray.append(variable)
}
}

return .array(flatArray)
}
}

public extension Variable {
/// Update the Variable's Value
/// - Returns: A new Variable with the type of T
Expand Down Expand Up @@ -153,7 +183,7 @@ extension Variable: ExpressibleByDictionaryLiteral {
}
}

extension AnyHashable {
public extension AnyHashable {
var variable: Variable {
if let variable = self as? Variable {
return variable
Expand Down

0 comments on commit a4b2b0c

Please sign in to comment.