Chase Sandmann
Chase Sandmann

Reputation: 5005

Can I return early (mid-function) in ClojureScript?

I have a function that is iterating over a moderately sized list of strings and is looking through some JSON returned from a server for the existence of a value in the data. The code will be run many times, so I want it to be fast. Is there any way I can return as soon as I find the value I'm looking for?

(defn find-type [js-data-set]
  (doseq [type all-type-strs]
    (when (aget js-data-set type)
      (return true)))) ; is there a way to do this?

Upvotes: 0

Views: 279

Answers (1)

Derek Slager
Derek Slager

Reputation: 13831

The built-in some function will find the first value matching a predicate, which fits this case rather nicely. More generally, you can use loop / recur, though that's rarely the most idiomatic option.

(defn find-type [js-data-set]
  (some #(goog.object/get js-data-set %) all-type-strs))

Upvotes: 4

Related Questions