Skip to content

Commit 7ab3bc7

Browse files
swannodettefogus
andauthored
port CLJ-2949: add req! (throwing get) and tests (#325)
* port CLJ-2949: add req! (throwing get) and tests Co-authored-by: Fogus <mefogus@gmail.com> * make REQ_NOT_FOUND private --------- Co-authored-by: Fogus <mefogus@gmail.com>
1 parent e7619af commit 7ab3bc7

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/main/cljs/cljs/core.cljs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2072,6 +2072,16 @@ reduces them without incurring seq initialization"
20722072
:else not-found)
20732073
not-found)))
20742074

2075+
(def ^:private REQ_NOT_FOUND #js {})
2076+
2077+
(defn req!
2078+
"Like arity-2 'get', but throws if key not present."
2079+
[m k]
2080+
(let [v (get m k REQ_NOT_FOUND)]
2081+
(if (identical? REQ_NOT_FOUND v)
2082+
(throw (js/Error. (str_ "Missing required key: " k)))
2083+
v)))
2084+
20752085
(declare PersistentHashMap PersistentArrayMap MapEntry)
20762086

20772087
(defn assoc

src/test/cljs/cljs/core_test.cljs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2012,4 +2012,13 @@
20122012

20132013
(deftest test-cljs-3415
20142014
(let [a 1 b 1]
2015-
(is (thrown? js/Error #{a b}))))
2015+
(is (thrown? js/Error #{a b}))))
2016+
2017+
(deftest test-req!
2018+
(let [m {:a 1, :b 2, :f nil, :g false, nil "nil"}]
2019+
(is (thrown? js/Error (req! m :e)))
2020+
(are [x y] (= x y)
2021+
(req! m :a) 1
2022+
(req! m nil) "nil"
2023+
(req! m :b) 2
2024+
(req! m :f) nil)))

0 commit comments

Comments
 (0)