Smart Map

The SmartMap class provides a simple way to cache the values of an arbitrary mapping function. This is useful when there is some expensive operation that is regularly performed on a specific set of values and caching the result gives a significant performance improvement. There is also a mechanism to invalidate the whole cache, as well as just specific keys.

Example

Below is an example which demonstrates how to use the SmartMap class.

local MyModule = select(2, ...).MyModule
local SmartMap = MyModule:From("LibTSMUtil"):IncludeClassType("SmartMap")

local function LookupValue(key)
   -- Assume this is an expensive and non-trivial operation
   return strupper(key)
end

local map = SmartMap.New("string", "string", LookupValue)

local reader = map:CreateReader(function(_, pendingChanges)
   for key, prevValue in pairs(pendingChanges) do print("CHANGE", key, prevValue) end
end)
print(reader["a"]) -- A
print(reader["b"]) -- B

-- Invalidate the mapping for just one key
map:ValueChanged("a")
-- CHANGE   a   A

-- Invalidate the entire map if the underlying operation changes significantly
map:Invalidate()
-- CHANGE   b   B

Memory Management

Both SmartMap and SmartMapReader objects are intended to never be GC’d and have a static lifecycle (i.e. one that’s equal to the lifecycle of the application).

API

class SmartMap: Class
staticmethod New(
    keyType: "number" | "string",
    valueType: "boolean" | "number" | "string",
    lookupFunc: fun(key: <K>): <V>
): SmartMap<<K>, <V>>

Create a new smart map object.

Parameters:
  • keyType ("number" | "string") – The type of the keys

  • valueType ("boolean" | "number" | "string") – The type of the values

  • lookupFunc (fun(key: <K>): <V>) – A function which looks up the value for a specific key

ValueChanged(self: SmartMap<<K>, <V>>, key: <K>)

Called when the value has changed for a given key to fetch the new one and notify the readers.

Parameters:

key (<K>) – The key which changed

SetCallbacksPaused(self: SmartMap, paused: boolean)

Pausese or unpauses reader callbacks.

Parameters:

paused (boolean) – Whether or not callbacks are paused

CreateReader(
    self: SmartMap<<K>, <V>>,
    callback?: fun(reader: SmartMapReader<<K>, <V>>, pendingChanges: table)
): SmartMapReader<<K>, <V>>

Creates a new reader.

Parameters:

callback? (fun(reader: SmartMapReader<<K>, <V>>, pendingChanges: table)) – The function to call when a value within the map changes

GetKeyType(self: SmartMap): "number" | "string"

Gets the type of the smart map’s keys.

GetValueType(self: SmartMap): "boolean" | "number" | "string"

Gets the type of the smart map’s values.

Iterator(self: SmartMap): fun(): string | number, boolean | string | number, table

Iterates over all data in the smart map.

Returns:

_1 (fun(): string | number, boolean | string | number) – Iterator with fields: key, value

Invalidate(self: SmartMap)

Invalidates all data in the smart map.