Skip to content

Commit

Permalink
feat(api): New, very useful utils in util added.
Browse files Browse the repository at this point in the history
These include:

- `xor(x: boolean, y: boolean)`: Simulates an xor logical operation.
- `strip_value`: Strip all or `n` values from a table.
  • Loading branch information
DrKJeff16 committed Jun 2, 2024
1 parent 34efef9 commit 00cec7a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lua/user/types/user/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
---@field notify fun(msg: string, lvl: NotifyLvl|VimNotifyLvl?, opts: NotifyOpts?)

---@class UserUtils
---@field strip_fields fun(T: table, fields: string|string[]): table
---@field xor fun(x: boolean, y: boolean): boolean
---@field strip_fields fun(T: table, values: string|string[]): table
---@field strip_values fun(T: table, values: any[], max_instances: integer?): table
---@field ft_set fun(s: string, bufnr: integer?): fun()
---@field ft_get fun(bufnr: integer?): string
---@field notify UserUtils.Notify
Expand Down
50 changes: 50 additions & 0 deletions lua/user/util/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ require('user.types.user.util')
---@diagnostic disable-next-line:missing-fields
local M = {}

function M.xor(x, y)
local is_bool = require('user.check.value').is_bool

if not is_bool({ x, y }, true) then
error('(user.util.xor): An argument is not of boolean type')
end

return (x and not y) or (not x and y)
end

function M.strip_fields(T, fields)
local is_tbl = require('user.check.value').is_tbl
local is_str = require('user.check.value').is_str
Expand Down Expand Up @@ -50,6 +60,46 @@ function M.strip_fields(T, fields)
return res
end

function M.strip_values(T, values, max_instances)
local is_tbl = require('user.check.value').is_tbl
local is_nil = require('user.check.value').is_nil
local is_str = require('user.check.value').is_str
local is_int = require('user.check.value').is_int
local empty = require('user.check.value').empty

if not is_tbl(T) then
error('(user.util.strip_values): Not a table')
elseif not is_tbl(values) or empty(values) then
error('(user.util.strip_values): No values given')
end

local xor = M.xor

max_instances = is_int(max_instances) and max_instances or 0

local res = {}

local count = 0

for k, v in next, T do
if xor(max_instances == 0, max_instances ~= 0 and max_instances > count) then
if not vim.tbl_contains(values, v) and is_int(k) then
table.insert(res, v)
elseif not vim.tbl_contains(values, v) then
res[k] = v
else
count = count + 1
end
elseif is_int(k) then
table.insert(res, v)
else
res[k] = v
end
end

return res
end

function M.ft_set(s, bufnr)
local is_int = require('user.check.value').is_int
local is_str = require('user.check.value').is_str
Expand Down

0 comments on commit 00cec7a

Please sign in to comment.