Skip to content

Commit

Permalink
added transferFrom() to Inventory
Browse files Browse the repository at this point in the history
  • Loading branch information
AlmasB committed Dec 10, 2021
1 parent a35e3ee commit 17bc460
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,27 @@ class Inventory<T>(

return isOK
}

/**
* Transfer [item] with [quantity] amount from [other] to this inventory.
*
* @return true if operation was successful
*/
@JvmOverloads fun transferFrom(other: Inventory<T>, item: T, quantity: Int = 1): Boolean {
if (isFull)
return false

if (!other.hasItem(item))
return false

if (other.getItemQuantity(item) < quantity)
return false

add(item, quantity = quantity)
other.incrementQuantity(item, -quantity)

return true
}
}

class ItemData<T> internal constructor(var userItem: T) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,4 +238,24 @@ class InventoryTest {

assertTrue(inventory.incrementQuantity("Hello", -10))
}

@Test
fun `Transfer from another inventory`() {
inventory = Inventory(5)

inventory.add("Hello", quantity = 5)

val other = Inventory<String>(6)

var result = other.transferFrom(inventory, "Hello", 4)

assertTrue(result)
assertThat(other.getItemQuantity("Hello"), `is`(4))
assertThat(inventory.getItemQuantity("Hello"), `is`(1))

// quantity only 1, so cannot transfer
result = other.transferFrom(inventory, "Hello", 4)

assertFalse(result)
}
}

0 comments on commit 17bc460

Please sign in to comment.