Skip to content
This repository has been archived by the owner on Nov 20, 2024. It is now read-only.

Commit

Permalink
Implement Dictionary.get
Browse files Browse the repository at this point in the history
  • Loading branch information
cxmeel committed Mar 15, 2024
1 parent 2eb4f21 commit 7934763
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/Dictionary/get.luau
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
--[=[
@within Dictionary
Retrieves a value from a dictionary using a key. If the key is a dot-separated string and the `separated` parameter is `true`, the function will traverse the dictionary using the parts of the string as keys. If `separated` is a string, it'll be used as the separator. If the key is not found, the function will return `nil`.
```lua
local dictionary = {
foo = {
bar = {
baz = "qux"
}
}
}
get(dictionary, "foo.bar.baz") -- nil
get(dictionary, "foo.bar.baz", true) -- "qux"
get(dictionary, "foo$bar$baz", "$") -- "qux"
```
]=]
local function get<K, V>(dictionary: { [K]: V }, key: K, separated: (string | boolean)?): V?
if not separated then
return dictionary[key]
end

local separator = type(separated) == "string" and separated or "."
local parts: { string } = (key :: any):split(separator)
local value: any = dictionary

while #parts > 0 do
local part = table.remove(parts, 1)
value = value[part]

if value == nil then
return nil
end
end

return value
end

return get
1 change: 1 addition & 0 deletions src/Dictionary/init.luau
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ local dictionary = {
freezeDeep = require("./freezeDeep"),
fromArrays = require("./fromArrays"),
fromEntries = require("./fromEntries"),
get = require("./get"),
has = require("./has"),
includes = require("./includes"),
keys = require("./keys"),
Expand Down

0 comments on commit 7934763

Please sign in to comment.