trim_spec.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. describe('vim.trim()', function()
  2. --- @param t number[]
  3. local function mean(t)
  4. assert(#t > 0)
  5. local sum = 0
  6. for _, v in ipairs(t) do
  7. sum = sum + v
  8. end
  9. return sum / #t
  10. end
  11. --- @param t number[]
  12. local function median(t)
  13. local len = #t
  14. if len % 2 == 0 then
  15. return t[len / 2]
  16. end
  17. return t[(len + 1) / 2]
  18. end
  19. --- @param f fun(t: number[]): table<number, number|string|table>
  20. local function measure(f, input, N)
  21. local stats = {} ---@type number[]
  22. for _ = 1, N do
  23. local tic = vim.uv.hrtime()
  24. f(input)
  25. local toc = vim.uv.hrtime()
  26. stats[#stats + 1] = (toc - tic) / 1000000
  27. end
  28. table.sort(stats)
  29. print(
  30. string.format(
  31. '\nN: %d, Min: %0.6f ms, Max: %0.6f ms, Median: %0.6f ms, Mean: %0.6f ms',
  32. N,
  33. math.min(unpack(stats)),
  34. math.max(unpack(stats)),
  35. median(stats),
  36. mean(stats)
  37. )
  38. )
  39. end
  40. local strings = {
  41. ['10000 whitespace characters'] = string.rep(' ', 10000),
  42. ['10000 whitespace characters and one non-whitespace at the end'] = string.rep(' ', 10000)
  43. .. '0',
  44. ['10000 whitespace characters and one non-whitespace at the start'] = '0'
  45. .. string.rep(' ', 10000),
  46. ['10000 non-whitespace characters'] = string.rep('0', 10000),
  47. ['10000 whitespace and one non-whitespace in the middle'] = string.rep(' ', 5000)
  48. .. 'a'
  49. .. string.rep(' ', 5000),
  50. ['10000 whitespace characters surrounded by non-whitespace'] = '0'
  51. .. string.rep(' ', 10000)
  52. .. '0',
  53. ['10000 non-whitespace characters surrounded by whitespace'] = ' '
  54. .. string.rep('0', 10000)
  55. .. ' ',
  56. }
  57. --- @type string[]
  58. local string_names = vim.tbl_keys(strings)
  59. table.sort(string_names)
  60. for _, name in ipairs(string_names) do
  61. it(name, function()
  62. measure(vim.trim, strings[name], 100)
  63. end)
  64. end
  65. end)