Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Last active August 17, 2024 14:35
Show Gist options
  • Save NikolaDespotoski/6bee2b740c0e10a24f4705fc142f5439 to your computer and use it in GitHub Desktop.
Save NikolaDespotoski/6bee2b740c0e10a24f4705fc142f5439 to your computer and use it in GitHub Desktop.
Search for largest composable parent given a selector
/**
* Searches largest parent with [LayoutCoordinates]
*
* @param selector property selector
*
* @return Largest parent in the tree [LayoutCoordinates] starting from calling
* receiver and searching up the tree until the last parent is visited. If receiver object doesn't
* have parent, it assumes this is the max.
*/
inline fun <reified P : Comparable<P>> LayoutCoordinates.maxOf(selector: LayoutCoordinates.() -> P): LayoutCoordinates {
var maxValue = this
var maxSelector = selector(this)
while (parentLayoutCoordinates != null) {
val next = requireNotNull(parentLayoutCoordinates)
val v = selector(next)
if (maxSelector < v) {
maxSelector = v
maxValue = next
}
}
return maxValue
}
/**
* Searches largest parent with [LayoutCoordinates]
*
* @param comparator [Comparator] that will compare [selector] types, if not [Comparable]
* @param selector property selector
*
* @return Largest parent in the tree [LayoutCoordinates] starting from calling
* receiver and searching up the tree until the last parent is visited. If receiver object doesn't
* have parent, it assumes this is the max.
*/
inline fun <reified P> LayoutCoordinates.maxOfWith(
comparator: Comparator<P>,
selector: LayoutCoordinates.() -> P
): LayoutCoordinates {
var maxValue = this
var maxSelector = selector(this)
while (parentLayoutCoordinates != null) {
val next = requireNotNull(parentLayoutCoordinates)
val v = selector(next)
if (comparator.compare(maxSelector, v) < 0) {
maxSelector = v
maxValue = next
}
}
return maxValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment