4 ms·
Part of the reason the Clojure code is ugly is because he's basically doing imperative code in a functional language. Here's my (highly annotated) take: (n
by grayrest 14y ago
Part of the reason the Clojure code is ugly is because he's basically doing imperative code in a functional language. Here's my (highly annotated) take:
(ns nurblizer.core
(:gen-class)
(:use compojure.core)
(:require
[clojure.string :as str]
[clostache.render :as clostache]
[ring.adapter.jetty :only run-jetty]
[compojure.handler :only site]))
;; main nurble stuff
(def nouns
(->> (-> (slurp (clojure.java.io/resource "nouns.txt")) ; read in nouns.txt
(str/split #"\n")) ; split by line
(map (comp str/trim str/upper-case)) ; feed the lines through upper-case and trim
set)) ; transform into a set
(def nurble-replacement-text "<span class=\"nurble\">nurble</span>")
(defn nurble-word [word]
(get nouns (str/upper-case word) nurble-replacement-text)) ; return word if word in set else nurble
(defn nurble [text]
(str/replace text #"\n|\w+" #(case % ; using anon func literal, switch on argument
"\n" "<br>" ; when arg is newline replace with br
(nurble-word %)))) ; otherwise nurble the argument (a word)
;; webserver stuff
(defn read-template [template-file]
(slurp (clojure.java.io/resource (str "templates/" template-file ".mustache"))))
(defn render
([template-file params]
(clostache/render (read-template template-file) params
{:_header (read-template "_header")
:_footer (read-template "_footer") })))
(defroutes main-routes
(GET "/" [] (render "index" {}))
(POST "/nurble" [text] (render "nurble" {:text (nurble text)})))
(defn -main []
(run-jetty (site main-routes) {:port 9000}))
The result is the same but the approach is different: build a set of uppercase nouns, define how each word in the text is handled, and do a single string replacement pass over the text to produce the output. Doing things like tokenizing the text and processing it as a seq or keeping the nouns lower case and producing upper case output are easy but seem like unnecessary complications so I left them out.
Note: In the grand tradition of the exercise, the webserver stuff is untested. I did repl-check the nurble part but was too lazy to set up a project.clj and have leiningen pull in the webserver deps.