forked from nikitabobko/AeroSpace
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f649909
commit 5aee831
Showing
3 changed files
with
59 additions
and
3 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
public typealias StringLogicalSegments = [StringLogicalSegment] | ||
extension StringLogicalSegments: Comparable { | ||
public static func < (lhs: Self, rhs: Self) -> Bool { | ||
for (a, b) in zip(lhs, rhs) { | ||
if a < b { | ||
return true | ||
} | ||
if a > b { | ||
return false | ||
} | ||
} | ||
if lhs.count != rhs.count { | ||
return lhs.count < rhs.count | ||
} | ||
return false | ||
} | ||
} | ||
|
||
public enum StringLogicalSegment: Comparable, Equatable { | ||
case string(String) | ||
case number(Int) | ||
|
||
public static func < (lhs: Self, rhs: Self) -> Bool { | ||
switch (lhs, rhs) { | ||
case (.string(let a), .string(let b)): a < b | ||
case (.number(let a), .number(let b)): a < b | ||
case (.number, _): true | ||
case (.string, _): false | ||
} | ||
} | ||
} | ||
|
||
public extension String { | ||
func toLogicalSegments() -> StringLogicalSegments { | ||
var currentSegment: String = "" | ||
var isPrevNumber: Bool = false // Initial value doesn't matter | ||
var result: [String] = [] | ||
for char in self { | ||
let isCurNumber = Int(char.description) != nil | ||
if isCurNumber != isPrevNumber && !currentSegment.isEmpty { | ||
result.append(currentSegment) | ||
currentSegment = "" | ||
} | ||
currentSegment.append(char) | ||
isPrevNumber = isCurNumber | ||
} | ||
if !currentSegment.isEmpty { | ||
result.append(currentSegment) | ||
} | ||
return result.map { Int($0).flatMap(StringLogicalSegment.number) ?? .string($0) } | ||
} | ||
} |