summaryrefslogtreecommitdiff
path: root/util.lua
diff options
context:
space:
mode:
Diffstat (limited to 'util.lua')
-rw-r--r--util.lua34
1 files changed, 34 insertions, 0 deletions
diff --git a/util.lua b/util.lua
index 99f8fe8..04e1bf6 100644
--- a/util.lua
+++ b/util.lua
@@ -91,4 +91,38 @@ function util.write_json_file(path, data)
f:close()
end
+-- merges tables `t' and `u', using key `k' for identity. the order from `u' is
+-- always respected, preserving the relative order from `t' when possible.
+function util.stable_kmerge(t, u, k)
+ local pos = {}
+ for i, v in ipairs(u) do
+ pos[v[k]] = i
+ end
+
+ local res = {}
+ local seen = {}
+ local function append(v)
+ if not seen[v[k]] then
+ res[#res+1] = v
+ seen[v[k]] = true
+ end
+ end
+
+ local ind = 1
+ for _, v in ipairs(t) do
+ if pos[v[k]] then
+ while ind <= pos[v[k]] do
+ append(u[ind])
+ ind = ind + 1
+ end
+ end
+ append(v)
+ end
+ for i = ind, #u do
+ append(u[i])
+ end
+
+ return res
+end
+
return util