-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathflatten.luau
More file actions
49 lines (38 loc) · 937 Bytes
/
flatten.luau
File metadata and controls
49 lines (38 loc) · 937 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
--!nonstrict
local maybeFreeze = require("../utils/maybeFreeze")
local function flattenImpl(dictionary: { [any]: any }, depth: number?)
local new = {}
for key, value in dictionary do
if type(value) == "table" and (not depth or depth > 0) then
local subDictionary = flattenImpl(value, depth and depth - 1)
for newKey, newValue in pairs(new) do
subDictionary[newKey] = newValue
end
new = subDictionary
else
new[key] = value
end
end
return new
end
--[=[
Returns a flattened dictionary by combining keys of the lowest depth.
If provided `depth`, the flattening will early-out.
```lua
Dictionary.flatten({
foo = 1,
foobar = {
bar = 2,
baz = {
etc = 3,
},
},
})
-- { foo = 1, bar = 2, etc = 3 }
```
@within Dictionary
]=]
local function flatten(dictionary: { [any]: any }, depth: number?): { [any]: any }
return maybeFreeze(flattenImpl(dictionary, depth))
end
return flatten