Skip to content

Commit

Permalink
Prefer .map over .flatMap when appropriate
Browse files Browse the repository at this point in the history
  • Loading branch information
1024jp committed Dec 19, 2024
1 parent 0db5f85 commit 24a3025
Show file tree
Hide file tree
Showing 19 changed files with 23 additions and 22 deletions.
4 changes: 2 additions & 2 deletions CotEditor/Sources/Document Window/Print/PrintTextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -381,10 +381,10 @@ final class PrintTextView: NSTextView {
String(localized: "Printed on \(.now, format: .dateTime)", comment: "print header/footer (%@ is date)")
case .lastModifiedDate:
self.documentInfo.lastModifiedDate
.flatMap { String(localized: "Last modified on \($0, format: .dateTime)", comment: "print header/footer (%@ is date)") }
.map { String(localized: "Last modified on \($0, format: .dateTime)", comment: "print header/footer (%@ is date)") }
?? ""
case .pageNumber:
NSPrintOperation.current.flatMap { String($0.currentPage) }
NSPrintOperation.current.map(\.currentPage).map(String.init)
case .none:
nil
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
//
// ---------------------------------------------------------------------------
//
// © 2016-2023 1024jp
// © 2016-2024 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -113,7 +113,7 @@ extension NSTextView {

// sanitize value
let scale = self.enclosingScrollView
.flatMap { $0.minMagnification...$0.maxMagnification }
.map { $0.minMagnification...$0.maxMagnification }
.map { newValue.clamped(to: $0) } ?? newValue

guard scale != self.scale else { return }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ extension MultiCursorEditing {
let ranges = self.insertionRanges.map { range -> NSRange in
let origin: Int? = origins
.firstIndex { range.upperBound == $0 || range.lowerBound == $0 }
.flatMap { origins.remove(at: $0) }
.map { origins.remove(at: $0) }

let (cursor, newOrigin): (Int, Int) = switch (forward, origin) {
case (false, range.lowerBound): (range.upperBound, range.lowerBound)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ extension NSTextView {
@discardableResult
final func replace(with string: String, range: NSRange, selectedRange: NSRange?, actionName: String? = nil) -> Bool {

let selectedRanges: [NSRange]? = selectedRange.flatMap { [$0] }
let selectedRanges: [NSRange]? = selectedRange.map { [$0] }

return self.replace(with: [string], ranges: [range], selectedRanges: selectedRanges, actionName: actionName)
}
Expand Down
2 changes: 1 addition & 1 deletion CotEditor/Sources/Document/Document.swift
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ extension Document: EditorSource {
savePanel.allowedContentTypes = self.fileType
.flatMap { self.fileNameExtension(forType: $0, saveOperation: .saveOperation) }
.flatMap { UTType(filenameExtension: $0) }
.flatMap { [$0] } ?? []
.map { [$0] } ?? []

// avoid the Hide Extension option removes actual filename extension (macOS 14, 2024-05)
savePanel.canSelectHiddenExtension = false
Expand Down
2 changes: 1 addition & 1 deletion CotEditor/Sources/Models/Snippet/FileDropItem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ extension FileDropItem {
// replace template
var dropText = self.format
.replacing(Variable.absolutePath.token, with: droppedFileURL.path)
.replacing(Variable.relativePath.token, with: documentURL.flatMap(droppedFileURL.path(relativeTo:)) ?? droppedFileURL.path)
.replacing(Variable.relativePath.token, with: documentURL.map(droppedFileURL.path(relativeTo:)) ?? droppedFileURL.path)
.replacing(Variable.filename.token, with: droppedFileURL.lastPathComponent)
.replacing(Variable.filenameWithoutExtension.token, with: droppedFileURL.deletingPathExtension().lastPathComponent)
.replacing(Variable.fileExtension.token, with: droppedFileURL.pathExtension)
Expand Down
2 changes: 1 addition & 1 deletion CotEditor/Sources/Models/Snippet/Snippet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ extension Snippet {
let insertions = ranges.map { range in
let selectedString = (string as NSString).substring(with: range)
let indent = string.rangeOfIndent(at: range.location)
.flatMap { (string as NSString).substring(with: $0) } ?? ""
.map((string as NSString).substring(with:)) ?? ""

let insertion = self.insertion(selectedString: selectedString, indent: indent)
let selectedRanges = insertion.selectedRanges.map { $0.shifted(by: range.location + offset) }
Expand Down
2 changes: 1 addition & 1 deletion CotEditor/Sources/Scanners/URLDetector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ extension NSTextStorage {
let links: [ValueRange<URL>] = try await Task.detached {
try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
.cancellableMatches(in: string, range: range)
.compactMap { match in match.url.flatMap { ValueRange(value: $0, range: match.range) } }
.compactMap { match in match.url.map { ValueRange(value: $0, range: match.range) } }
}.value

try Task.checkCancellation()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ extension SettingFileManaging {
throw .empty
}

if (settingName + (Self.fileType.preferredFilenameExtension.flatMap({ "." + $0 }) ?? "")).utf16.count > Int(NAME_MAX) {
if (settingName + (Self.fileType.preferredFilenameExtension.map({ "." + $0 }) ?? "")).utf16.count > Int(NAME_MAX) {
throw .tooLong
}

Expand Down
2 changes: 1 addition & 1 deletion CotEditor/Sources/Setting Managers/SnippetManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ import URLUtils
guard menu.items.count > 1 || !self.snippets.isEmpty else { return }

let generalSnippets = self.snippets.filter { $0.scope == nil }
let scopeSnippets = self.scope.flatMap { scope in self.snippets.filter { $0.scope == scope } } ?? []
let scopeSnippets = self.scope.map { scope in self.snippets.filter { $0.scope == scope } } ?? []

let editItem = menu.items.last!
let action = #selector((any SnippetInsertable).insertSnippet)
Expand Down
2 changes: 1 addition & 1 deletion CotEditor/Sources/Setting Managers/SyntaxManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ final class SyntaxManager: SettingFileManaging, @unchecked Sendable {
}

// update internal cache
let change: SettingChange = oldName.flatMap { .updated(from: $0, to: name) } ?? .added(name)
let change: SettingChange = oldName.map { .updated(from: $0, to: name) } ?? .added(name)
self.updateSettingList(change: change)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ final class MultipleReplaceViewController: NSViewController {
var client: NSTextView? {

NSApp.mainWindow?.firstResponder
.flatMap { sequence(first: $0, next: \.nextResponder) }?
.map { sequence(first: $0, next: \.nextResponder) }?
.compactMap { $0 as? NSTextView }
.first { $0 is any TextFinderClient }
}
Expand Down
2 changes: 1 addition & 1 deletion CotEditor/Sources/Views/AppKit/DraggableHostingView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ final class DraggableHostingView<Content>: NSHostingView<Content> where Content:
/// The area the receiver located in the superview.
private var preferredEdge: Edge? {

self.superview.flatMap { superview in
self.superview.map { superview in
Edge(horizontal: superview.frame.width/2 < self.frame.midX ? .right : .left,
vertical: superview.frame.height/2 < self.frame.midY ? .top : .bottom)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public struct CharacterInfo: Sendable {
public var pictureCharacter: Character? {

self.character.unicodeScalars.count == 1 // ignore CRLF
? self.character.unicodeScalars.first?.pictureRepresentation.flatMap(Character.init)
? self.character.unicodeScalars.first?.pictureRepresentation.map(Character.init)
: nil
}

Expand Down
2 changes: 1 addition & 1 deletion Packages/EditorCore/Sources/StringUtils/BracePair.swift
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public extension StringProtocol {
assert(beginIndex >= self.startIndex)

// avoid (endIndex == self.startIndex)
guard !self.isEmpty, endIndex.flatMap({ $0 > self.startIndex }) != false else { return nil }
guard !self.isEmpty, endIndex.map({ $0 > self.startIndex }) != false else { return nil }

let endIndex = self.index(before: endIndex ?? self.endIndex)

Expand Down
5 changes: 3 additions & 2 deletions Packages/EditorCore/Sources/Syntax/Syntax.swift
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ public struct Syntax: Equatable, Sendable {
for highlight in item.value {
// extract paired delimiters such as quotes
if !highlight.isRegularExpression,
let pair = highlight.end.flatMap({ Pair(highlight.begin, $0) }),
let pair = highlight.end.map({ Pair(highlight.begin, $0) }),
pair.begin == pair.end,
pair.begin.rangeOfCharacter(from: .alphanumerics) == nil, // symbol
Set(pair.begin).count == 1, // consists of the same characters
Expand Down Expand Up @@ -347,7 +347,8 @@ public struct Syntax: Equatable, Sendable {
completions
} else {
// from normal highlighting words
SyntaxType.allCases.map(Self.highlightKeyPath(for:))
SyntaxType.allCases
.map(Self.highlightKeyPath(for:))
.flatMap { self[keyPath: $0] }
.filter { $0.end == nil && !$0.isRegularExpression }
.map { $0.begin.trimmingCharacters(in: .whitespacesAndNewlines) }
Expand Down
2 changes: 1 addition & 1 deletion Packages/EditorCore/Sources/URLUtils/String+Filename.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public extension Collection<String> {
func createAvailableName(for proposedName: String, suffix: String? = nil) -> String {

let components = proposedName.numberingComponents(suffix: suffix)
let baseName = String(components.base) + (suffix.flatMap { " " + $0 } ?? "")
let baseName = String(components.base) + (suffix.map { " " + $0 } ?? "")

guard components.count != nil || self.contains(baseName) else { return baseName }

Expand Down
2 changes: 1 addition & 1 deletion Packages/EditorCore/Sources/URLUtils/URL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public extension FileManager {

public extension URL {

private static let homeDirectory = getpwuid(getuid())?.pointee.pw_dir.flatMap { String(cString: $0) } ?? NSHomeDirectory()
private static let homeDirectory = getpwuid(getuid())?.pointee.pw_dir.map { String(cString: $0) } ?? NSHomeDirectory()


/// A path string that replaces the user's home directory with a tilde (~) character.
Expand Down
2 changes: 1 addition & 1 deletion Packages/MacUI/Tests/ShortcutTests/ShortcutTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ struct ShortcutTests {
let f10 = try #require(String(NSEvent.SpecialKey.f10.unicodeScalar))
#expect(Shortcut(keySpecChars: "@" + f10)?.symbol == "⌘ F10")

let delete = try #require(UnicodeScalar(NSDeleteCharacter).flatMap(String.init))
let delete = try #require(UnicodeScalar(NSDeleteCharacter).map(String.init))
#expect(Shortcut(keySpecChars: "@" + delete)?.symbol == "⌘ ⌫")

// test creation
Expand Down

0 comments on commit 24a3025

Please sign in to comment.