diff --git a/src/main/cljs/cljs/core.cljs b/src/main/cljs/cljs/core.cljs index 993a5d5fe..f97d4c7bc 100644 --- a/src/main/cljs/cljs/core.cljs +++ b/src/main/cljs/cljs/core.cljs @@ -2072,6 +2072,16 @@ reduces them without incurring seq initialization" :else not-found) not-found))) +(def ^:private REQ_NOT_FOUND #js {}) + +(defn req! + "Like arity-2 'get', but throws if key not present." + [m k] + (let [v (get m k REQ_NOT_FOUND)] + (if (identical? REQ_NOT_FOUND v) + (throw (js/Error. (str_ "Missing required key: " k))) + v))) + (declare PersistentHashMap PersistentArrayMap MapEntry) (defn assoc diff --git a/src/test/cljs/cljs/core_test.cljs b/src/test/cljs/cljs/core_test.cljs index 8bff60d3b..933f87781 100644 --- a/src/test/cljs/cljs/core_test.cljs +++ b/src/test/cljs/cljs/core_test.cljs @@ -2012,4 +2012,13 @@ (deftest test-cljs-3415 (let [a 1 b 1] - (is (thrown? js/Error #{a b})))) \ No newline at end of file + (is (thrown? js/Error #{a b})))) + +(deftest test-req! + (let [m {:a 1, :b 2, :f nil, :g false, nil "nil"}] + (is (thrown? js/Error (req! m :e))) + (are [x y] (= x y) + (req! m :a) 1 + (req! m nil) "nil" + (req! m :b) 2 + (req! m :f) nil)))