func.lua 2.0 KB

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