Skip to content

Instantly share code, notes, and snippets.

@JYCabello
Last active December 2, 2019 07:32
Show Gist options
  • Save JYCabello/03364cd6d830e003502f647582974851 to your computer and use it in GitHub Desktop.
Save JYCabello/03364cd6d830e003502f647582974851 to your computer and use it in GitHub Desktop.
Functional approach to insertOrUpdate
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
fun insertOrUpdate(fruit: FruitMetadata): Int =
findByAuthorityId(fruit.fruitAuthorityId)
.fold({ findByCouncilId(fruit.fruitCouncilId) }, ::Some)
.fold({ findByName(fruit.name) }, ::Some)
.fold({ insert(fruit) }, { update(it, fruit) })
fun findByAuthorityId(authorityId: Int): Option<Int> = None
fun findByCouncilId(councilId: Int): Option<Int> = None
fun findByName(name: String): Option<Int> = None
fun insert(fruit: FruitMetadata): Int = 1
fun update(id: Int, fruit: FruitMetadata): Int = id
data class FruitMetadata(val color: String, val fruitAuthorityId: Int, val fruitCouncilId: Int, val name: String, val shape: String)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment