All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lightningkite.ktordb.CollectionChanges.kt Maven / Gradle / Ivy

The newest version!
@file:SharedCode

package com.lightningkite.ktordb

import com.lightningkite.khrysalis.Equatable
import com.lightningkite.khrysalis.IsCodableAndHashable
import com.lightningkite.khrysalis.JsName
import com.lightningkite.khrysalis.SharedCode
import kotlinx.serialization.Serializable
import java.util.ArrayList

@Serializable
data class CollectionChanges(
    val changes: List> = listOf(),
    val replace: List? = null
) {
    @JsName("pair")
    constructor(old: T? = null, new: T? = null) : this(
        changes = if (old != null || new != null) listOf(
            EntryChange(
                old,
                new
            )
        ) else listOf()
    )
}

fun , ID : Comparable> List.apply(changes: CollectionChanges): List {
    if (changes.replace != null) {
        return changes.replace
    }
    val changeable = this.toMutableList()
    for (change in changes.changes) {
        change.old?.let { old -> changeable.removeAll { it._id == old._id } }
        change.new?.let { new -> changeable.add(new) }
    }
    return changeable
}

// This will not convert well. Manually add the type argument to the return EntryChange on the swift side. "EntryChange"
inline fun  CollectionChanges.map(mapper: (T) -> B): CollectionChanges {
    return CollectionChanges(changes = changes.map { it.map(mapper) }, replace = replace?.map(mapper))
}