Skip to content

Commit

Permalink
♻️ Make property update easier
Browse files Browse the repository at this point in the history
  • Loading branch information
sleepyfran committed Jul 13, 2024
1 parent 5a18af1 commit 69c9c03
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
29 changes: 29 additions & 0 deletions src/Duets.Entities/Item.fs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module Duets.Entities.Item

open Microsoft.FSharp.Reflection

module Property =
/// Attempts to retrieve the main property of the given item, if any.
let tryMain item = item.Properties |> List.tryHead
Expand All @@ -10,6 +12,33 @@ module Property =
/// Checks if the given item has a property that satisfies the given function.
let has fn item = item.Properties |> List.exists fn

/// Removes the current given property from the item and re-adds the updated
/// one, returning the updated item. The matching of the property is done
/// against the name of the case via reflection, so it'd match even if
/// the values inside the property are different.
let update property item =
let updatedPropertyInfo, _ =
FSharpValue.GetUnionFields(property, property.GetType())

item.Properties
|> List.filter (fun currentProperty ->
let currentPropertyInfo, _ =
FSharpValue.GetUnionFields(
currentProperty,
currentProperty.GetType()
)

currentPropertyInfo.Name <> updatedPropertyInfo.Name)
|> (@) [ property ]

/// Updates the given item by removing the current property that matches
/// the given one, and re-adds the updated property returning the updated item.
let updateProperty property item =
let updatedProperties = Property.update property item

{ item with
Properties = updatedProperties }

module Beer =
/// Creates a beer item.
let create brand amount alcoholContent =
Expand Down
11 changes: 1 addition & 10 deletions src/Duets.Simulation/Interactions/Items/Actions/Read.Action.fs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,7 @@ let private read' (item: Item) book state =
{ book with
ReadProgress = updatedReadPercentage }

let updatedProperties =
item.Properties
|> List.filter (function
| Readable _ -> false
| _ -> true)
|> (@) [ Readable(Book updatedBook) ]

let updatedItem =
{ item with
Properties = updatedProperties }
let updatedItem = Item.updateProperty (Readable(Book updatedBook)) item

Diff(item, updatedItem) |> ItemChangedInCharacterInventory

Expand Down

0 comments on commit 69c9c03

Please sign in to comment.