Skip to content

Commit 3fc2cbd

Browse files
Add firstNonNilMap and lastNonNilMap
1 parent 9688215 commit 3fc2cbd

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Sources/DeltaModule/Delta.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,50 @@ extension Delta where Element: ~Copyable {
172172
}
173173
}
174174

175+
/// Applies a transformation to the elements in source–target order and returns the first non-`nil` result.
176+
///
177+
/// Returns `nil` when the transformation returns `nil` for all elements.
178+
@inlinable
179+
public func firstNonNilMap<E, T: ~Copyable>(
180+
_ transform: (borrowing Element) throws(E) -> T?,
181+
) throws(E) -> T? {
182+
switch self {
183+
case .source(let element):
184+
try transform(element)
185+
case .target(let element):
186+
try transform(element)
187+
case .transition(source: let source, target: let target):
188+
if let result = try transform(source) {
189+
result
190+
}
191+
else {
192+
try transform(target)
193+
}
194+
}
195+
}
196+
197+
/// Applies a transformation to the elements in target–source order and returns the first non-`nil` result.
198+
///
199+
/// Returns `nil` when the transformation returns `nil` for all elements.
200+
@inlinable
201+
public func lastNonNilMap<E, T: ~Copyable>(
202+
_ transform: (borrowing Element) throws(E) -> T?,
203+
) throws(E) -> T? {
204+
switch self {
205+
case .source(let element):
206+
try transform(element)
207+
case .target(let element):
208+
try transform(element)
209+
case .transition(source: let source, target: let target):
210+
if let result = try transform(target) {
211+
result
212+
}
213+
else {
214+
try transform(source)
215+
}
216+
}
217+
}
218+
175219
/// Resolves the delta to a single element, favoring the element on the given side.
176220
///
177221
/// If the favored element is not available, the other element is returned.

Sources/DeltaModule/Documentation.docc/Delta.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
- ``last``
3333
- ``resolve(favoring:)``
3434
- ``coalesce(_:)``
35+
- ``firstNonNilMap(_:)``
36+
- ``lastNonNilMap(_:)``
3537

3638
### Composition
3739

0 commit comments

Comments
 (0)