robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesrefactor(lsp): drop once(), use _memoize() #37829fd69b71119

master
1.9 KiB40 linesraw
1local M = {}
2
3-- TODO(lewis6991): Private for now until:
4-- - There are other places in the codebase that could benefit from this
5--   (e.g. LSP), but might require other changes to accommodate.
6-- - I don't think the story around `hash` is completely thought out. We
7--   may be able to have a good default hash by hashing each argument,
8--   so basically a better 'concat'.
9-- - Need to support multi level caches. Can be done by allow `hash` to
10--   return multiple values.
11--
12--- Memoizes a function {fn} using {hash} to hash the arguments.
13---
14--- Internally uses a |lua-weaktable| to cache the results of {fn} meaning the
15--- cache will be invalidated whenever Lua does garbage collection.
16---
17--- The cache can also be manually invalidated by calling `:clear()` on the returned object.
18--- Calling this function with no arguments clears the entire cache; otherwise, the arguments will
19--- be interpreted as function inputs, and only the cache entry at their hash will be cleared.
20---
21--- The memoized function returns shared references so be wary about
22--- mutating return values.
23---
24--- @generic F: function
25--- @param hash integer|string|function Hash function to create a hash to use as a key to
26---     store results. Possible values:
27---     - When integer, refers to the index of a {fn} argument (of any type) to hash.
28---     - When function, is evaluated using the same arguments passed to {fn}.
29---     - When "concat", hash is determined by string-concatenating all {fn} arguments.
30---     - When "concat-n", hash is determined by string-concatenating the first n {fn} arguments.
31---
32--- @param fn F Function to memoize.
33--- @param weak? boolean Use a weak table (default `true`)
34--- @return F # Memoized version of {fn}
35function M._memoize(hash, fn, weak)
36  -- this is wrapped in a function to lazily require the module
37  return require('vim.func._memoize')(hash, fn, weak)
38end
39
40return M