Fix #470: Expose find() for associative container types (#668)

Add a native find() method to unique associative containers (e.g., Map)
that returns the mapped value if the key exists, or an undefined
Boxed_Value if not. This allows checking for key existence without
mutating the container (unlike operator[]) or requiring exception
handling (unlike at()).

Co-authored-by: leftibot <leftibot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
leftibot 2026-04-11 18:57:26 -06:00 committed by GitHub
parent 0d1ceed05d
commit dcdab50efd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 25 additions and 0 deletions

View File

@ -85,6 +85,15 @@ namespace chaiscript::bootstrap::standard_library {
return t_target.count(t_key);
}
template<typename T>
Boxed_Value find(const T &t_target, const typename T::key_type &t_key) {
const auto itr = t_target.find(t_key);
if (itr != t_target.end()) {
return Boxed_Value(itr->second);
}
return Boxed_Value();
}
template<typename T>
void insert(T &t_target, const T &t_other) {
t_target.insert(t_other.begin(), t_other.end());
@ -355,6 +364,7 @@ namespace chaiscript::bootstrap::standard_library {
template<typename ContainerType>
void unique_associative_container_type(const std::string & /*type*/, Module &m) {
m.add(fun(detail::count<ContainerType>), "count");
m.add(fun(detail::find<ContainerType>), "find");
using erase_ptr = size_t (ContainerType::*)(const typename ContainerType::key_type &);

15
unittests/map_find.chai Normal file
View File

@ -0,0 +1,15 @@
auto m = ["k":"v"]
// find existing key returns the value
assert_equal("v", m.find("k"))
// find missing key returns undef
assert_true(m.find("missing").is_var_undef())
// find does not mutate the map
m.find("other")
assert_equal(1, m.size())
// find works with in-place map
assert_equal("v", ["k":"v"].find("k"))