dartx icon indicating copy to clipboard operation
dartx copied to clipboard

#117 add: Iterable.modifyWhere() and Iterable.modifyFirstWhere()

Open VKBobyr opened this issue 4 years ago • 1 comments

Resolves #117

VKBobyr avatar Jan 02 '22 21:01 VKBobyr

The two lambdas that needs to be passed in modifyWhere feel redundant. Why not have one? Two versions in the kotlin world popped into my mind:

inline fun <T> MutableList<T>.mutate(transform: (T) -> T): MutableList<T> {
    return mutateIndexed { _, t -> transform(t) }
}

inline fun <T> MutableList<T>.mutateIndexed(transform: (Int, T) -> T): MutableList<T> {
    val iterator = listIterator()
    var i = 0
    while (iterator.hasNext()) {
        iterator.set(transform(i++, iterator.next()))
    }
    return this
}

or

fun <T> MutableList<T>.mapInPlace(mutator: (T) -> (T)) {
    this.forEachIndexed { i, value ->
        val changedValue = mutator(value)

        if (value != changedValue) {
            this[i] = changedValue
        }
    }
}

passsy avatar Apr 12 '22 11:04 passsy