neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

trim_spec.lua (1909B)


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