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