Skip to content

[Suggestion] Add option for generating key #393

@rChaoz

Description

@rChaoz

Problem

Objects/arrays work as keys, but only by reference, so this doesn't work:

cache.set(["category", "name"], value)
cache.get(["category", "name"])  // undefined

Workaround is to manually transform stuff to strings when calling cache functions, for example

cache.set(`${category}/${name}`, value)
cache.get(`${category}/${name}`)  // value

This gets trickier if using fetch, or more complex values that can't just be concatenated:

const cache = new LRUCache<string, string>({
    max: 1000,
    async fetchMethod(key) {
        const [category, name] = JSON.parse(key)
        return await compute(category, name)
    }
})

await cache.fetch(JSON.stringify([category, name]))

Suggestion

Add an option to generate the internal key used. This allows the visible key type to be anything, while using a different, internal type, for the actual key. This would require a single method (key → internal key), but to make it work with find (and maybe other APIs that provide keys directly), a reverse is also needed:

// 4th generic for internal key type
const cache = new LRUCache<[string, string], string, undefined, string>({
    max: 1000,
    async fetchMethod([category, name]) {
        return await compute(category, name)
    },
    keyMap: [JSON.stringify, JSON.parse],
    // Or even allow an object with stringify/parse methods, since the JSON interface is used by other serialization libraries too
    keyMap: JSON,
})

await cache.fetch([category, name])

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions