daily pastebin goal
30%
SHARE
TWEET

Untitled

a guest Nov 20th, 2018 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface TreeNode<T> {
  2.     val T.subNodes: Sequence<T>
  3. }
  4.  
  5. interface NodeSearchStrategy<T> {
  6.     fun TreeNode<T>.sequence(from: Sequence<T>, next: (Sequence<T>) -> Sequence<T>): Sequence<T>
  7.     fun TreeNode<T>.sequence(from: Sequence<T>): Sequence<T> = sequence(from) { sequence(it) }
  8. }
  9.  
  10. sealed class BFS<T> : NodeSearchStrategy<T> {
  11.     override fun TreeNode<T>.sequence(from: Sequence<T>, next: (Sequence<T>) -> Sequence<T>): Sequence<T> = sequence {
  12.         var list = listOf<T>()
  13.         yieldAll(from.map { it.also { list += it } })
  14.         if (list.isNotEmpty()) yieldAll(next(list.asSequence().flatMap { it.subNodes }))
  15.     }
  16.  
  17.     companion object : BFS<Any>() {
  18.         operator fun <T> invoke() = this as BFS<T>
  19.     }
  20. }
  21.  
  22.  
  23. sealed class DFS<T> : NodeSearchStrategy<T> {
  24.     override fun TreeNode<T>.sequence(from: Sequence<T>, next: (Sequence<T>) -> Sequence<T>): Sequence<T> =
  25.             from.flatMap { next(it.subNodes) + it }
  26.  
  27.     companion object : DFS<Any>() {
  28.         operator fun <T> invoke() = this as DFS<T>
  29.     }
  30. }
  31.  
  32.  
  33.  
  34. object ViewChildren : TreeNode<View> {
  35.     override val View.subNodes: Sequence<View>
  36.         get() = sequence {
  37.             if (this is ViewGroup)
  38.                 for (i in 0 until childCount)
  39.                     yield(getChildAt(i))
  40.         }
  41. }
  42.  
  43. inline fun <reified T : View> ViewGroup.first(strategy: NodeSearchStrategy<View> = DFS()): T? = strategy.run {
  44.     ViewChildren.sequence(sequenceOf(this@first)).filterIsInstance<T>().firstOrNull()
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top