Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add executeOnFirstMatch and toggle #302

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
add executeOnFirstMatch and toggle
  • Loading branch information
yveskalume committed Feb 12, 2023
commit ff17eeca88e4290d625aed0ea9e291890ba704e7
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,26 @@ inline fun <T> List<T>.forEachReversedWithIndex(
action(i, get(i))
}
}

/**
* Execute an [action] to the first item witch matches the [predicate].
* Do nothing if there's not match
*/
fun <T> Collection<T>.executeOnFirstMatch(predicate:(T) -> Boolean,action: (T) -> Unit) {
val matched = this.firstOrNull(predicate)
if (matched != null) {
action(matched)
}
}

/**
* Toggle an [item] from a MutableList.
*/
fun <T> MutableList<T>.toggle(item: T): List<T> {
if (this.contains(item)) {
this.remove(item)
} else {
this.add(item)
}
return this
}