Christian Bangert
Christian Bangert

Reputation: 710

Getting a string value from vector of vectors

Given this data structure

(def file-types 
 [["figure" "Figure"]
  ["video" "Video"]
  ["graphic" "Inline Graphic/Custom Artwork"]
  ["other" "Other"]])

Given this "key"

(def file-type "graphic")

This there a better way of getting the second value from the corresponding tuple?

(defn get-file-label [file-types file-type]
  (second (peek (filterv #(= (% 0) file-type) file-types))))

Expected output "Inline Graphic/Custom Artwork"

Upvotes: 0

Views: 139

Answers (1)

Alan Thompson
Alan Thompson

Reputation: 29958

Easy peasy! Just convert the sequence of string pairs into a map for fast lookup:

(ns tst.demo.core
  (:use tupelo.core tupelo.test))

(dotest
  (let [file-types [["figure" "Figure"]
                    ["video" "Video"]
                    ["graphic" "Inline Graphic/Custom Artwork"]
                    ["other" "Other"]]
        file->type (into {} file-types)]
    (is= (file->type "graphic") "Inline Graphic/Custom Artwork")))

Be sure to review the Clojure CheatSheet and this list of other docs.

Upvotes: 3

Related Questions