robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
2.4 KiB74 linesraw
1-- Test suite for vim.list
2local t = require('test.testutil')
3local describe, it = t.describe, t.it
4local eq = t.eq
5
6describe('vim.list', function()
7  it('vim.list.unique()', function()
8    eq({ 1, 2, 3, 4, 5 }, vim.list.unique({ 1, 2, 2, 3, 4, 4, 5 }))
9    eq({ 1, 2, 3, 4, 5 }, vim.list.unique({ 1, 2, 3, 4, 4, 5, 1, 2, 3, 2, 1, 2, 3, 4, 5 }))
10    eq({ 1, 2, 3, 4, 5, field = 1 }, vim.list.unique({ 1, 2, 2, 3, 4, 4, 5, field = 1 }))
11
12    -- Not properly defined, but test anyway
13    -- luajit evaluates #t as 7, whereas Lua 5.1 evaluates it as 12
14    local r = vim.list.unique({ 1, 2, 2, 3, 4, 4, 5, nil, 6, 6, 7, 7 })
15    if jit then
16      eq({ 1, 2, 3, 4, 5, nil, nil, nil, 6, 6, 7, 7 }, r)
17    else
18      eq({ 1, 2, 3, 4, 5, nil, 6, 7 }, r)
19    end
20
21    eq(
22      { { 1 }, { 2 }, { 3 } },
23      vim.list.unique({ { 1 }, { 1 }, { 2 }, { 2 }, { 3 }, { 3 } }, function(x)
24        return x[1]
25      end)
26    )
27
28    eq({ { id = 1 }, { id = 2 } }, vim.list.unique({ { id = 1 }, { id = 2 }, { id = 1 } }, 'id'))
29  end)
30
31  --- Generate a list like { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, ...}.
32  ---@param num integer
33  local function gen_list(num)
34    ---@type integer[]
35    local list = {}
36    for i = 1, num do
37      for _ = 1, i do
38        list[#list + 1] = i
39      end
40    end
41    return list
42  end
43
44  --- Index of the last {num}.
45  --- Mathematically, a triangular number.
46  ---@param num integer
47  local function index(num)
48    return math.floor((math.pow(num, 2) + num) / 2)
49  end
50
51  it("vim.list.bisect(..., { bound = 'lower' })", function()
52    local num = math.random(100)
53    local list = gen_list(num)
54
55    local target = math.random(num)
56    eq(vim.list.bisect(list, target, { bound = 'lower' }), index(target - 1) + 1)
57    eq(vim.list.bisect(list, num + 1, { bound = 'lower' }), index(num) + 1)
58
59    local dict_list = { { value = 1 }, { value = 2 }, { value = 2 }, { value = 3 } }
60    eq(2, vim.list.bisect(dict_list, { value = 2 }, { key = 'value', bound = 'lower' }))
61  end)
62
63  it("vim.list.bisect(..., bound = { 'upper' })", function()
64    local num = math.random(100)
65    local list = gen_list(num)
66
67    local target = math.random(num)
68    eq(vim.list.bisect(list, target, { bound = 'upper' }), index(target) + 1)
69    eq(vim.list.bisect(list, num + 1, { bound = 'upper' }), index(num) + 1)
70
71    local dict_list = { { value = 1 }, { value = 2 }, { value = 2 }, { value = 3 } }
72    eq(4, vim.list.bisect(dict_list, { value = 2 }, { key = 'value', bound = 'upper' }))
73  end)
74end)