Skip to content

ForKeys state object since v0.2

Processes a table from another state object by transforming its keys only.

(
    input: CanBeState<{[KI]: V}>,
    keyProcessor: (KI, M) -> (KO, M),
    keyDestructor: ((KO, M) -> ())?
) -> ForKeys<KI, KO, V, M>

Parameters

  • input: CanBeState<{[KI]: V}> - the table to be processed, either as a state object or a constant value
  • keyProcessor: (KI, M) -> (KO, M) - transforms input keys into new keys, optionally providing metadata for the destructor alone
  • keyDestructor: ((KO, M) -> ())? - disposes of values generated by keyProcessor when they are no longer in use

Object Methods

since v0.2

ForKeys:get()

Returns the current value stored in the state object.

If dependencies are being captured (e.g. inside a computed callback), this state object will also be added as a dependency.

(asDependency: boolean?) -> {[KO]: V}

Example Usage

local data = Value({
    one = 1,
    two = 2,
    three = 3,
    four = 4
})

local transformed = ForKeys(data, function(key)
    local newKey = string.upper(key)
    return newKey
end)

print(transformed:get()) --> {ONE = 1, TWO = 2 ... }

Dependency Management

ForKeys objects automatically detect dependencies used inside their callback each time their callback runs. This means, when you use a function like :get() on a state object, it will register that state object as a dependency:

local multiplier = Value(2)
local data = Value({1, 2, 3, 4, 5})

local scaledData = ForKeys(data, function(key)
    -- Fusion detects you called :get() on `multiplier`, and so adds `multiplier`
    -- as a dependency specifically for this key.
    return key * multiplier:get()
end)

When that dependency changes value, the specific keys using that value are recalculated.

See the Computed docs for specifics on how dependency management works.


Destructors

The keyDestructor callback, if provided, is called when this object swaps out an old key for a newly-generated one. It is called with the old key as the first parameter, and - if provided - an extra value returned from keyProcessor as a customisable second parameter.

Destructors are required when working with data types that require destruction, such as instances. Otherwise, they are optional, so not all calculations have to specify destruction behaviour.

Fusion guarantees that values passed to destructors by default will never be used again by the library, so it is safe to finalise them. This does not apply to the customisable second parameter, which the user is responsible for handling properly.


Optimisations

ForKeys does not allow access to the values of the input table. This guarantees that all generated keys are completely independent of any values. This means keys only need to be calculated when they're added to the input table - all other changes are simply forwarded to the output table. Since keys are also unique, all calculations are unique, so caching and reuse are not required.

Back to top