Last active
          January 8, 2024 16:01 
        
      - 
      
 - 
        
Save guissalustiano/8d6516226474a15166b6e1c0b3258a96 to your computer and use it in GitHub Desktop.  
    Naive `Iterable<T>.chunkedBy` implemention to Kotlin
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | inline fun <T> Iterable<T>.chunkedBy( | |
| predicate: (T) -> Boolean | |
| ): List<List<T>> { | |
| val iterator = this.iterator() | |
| if (!iterator.hasNext()) { | |
| return emptyList() | |
| } | |
| var lastElem = iterator.next() | |
| var lastList = mutableListOf(lastElem) | |
| val acc = mutableListOf<MutableList<T>>(lastList) | |
| for(elem in iterator) { | |
| if (predicate(lastElem) == predicate(elem)) { | |
| lastList.add(elem) | |
| } else { | |
| lastList = mutableListOf(elem) | |
| acc.add(lastList) | |
| } | |
| lastElem = elem | |
| } | |
| return acc.map{it.toList()}.toList() | |
| } | |
| fun main() { | |
| val a = listOf(1, 2, 2, 3, 3, 5, 5, 6) | |
| print(a.chunkedBy{it % 2 == 0}) | |
| // [[1], [2, 2], [3, 3, 5, 5], [6]] | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment