diff --git a/include/chaiscript/dispatchkit/bootstrap_stl.hpp b/include/chaiscript/dispatchkit/bootstrap_stl.hpp index 5bbc17e0..967344d7 100644 --- a/include/chaiscript/dispatchkit/bootstrap_stl.hpp +++ b/include/chaiscript/dispatchkit/bootstrap_stl.hpp @@ -85,6 +85,15 @@ namespace chaiscript::bootstrap::standard_library { return t_target.count(t_key); } + template + 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 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 void unique_associative_container_type(const std::string & /*type*/, Module &m) { m.add(fun(detail::count), "count"); + m.add(fun(detail::find), "find"); using erase_ptr = size_t (ContainerType::*)(const typename ContainerType::key_type &); diff --git a/unittests/map_find.chai b/unittests/map_find.chai new file mode 100644 index 00000000..d8d3030e --- /dev/null +++ b/unittests/map_find.chai @@ -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"))