As one of my first "real" projects in Clojure(Script), I took one of the programming exercises from my Algebra II textbooks. The goal is to receive two 2D coordinates from the user and calculate the distance, midpoint, and slope of the resulting line segment. What I have written fulfills the requirements, but I feel like it is very repetitive (e.g. pt1-str pt2-str, or x1 y1 x2 y2). I have only posted the cljs code, since nothing else is relevant to the problem, and I'm fairly confident that the other code is ok.

(ns project2.core
    (:require [reagent.core :as r]
              [clojure.string :as str]
              [cljs.pprint :as pprint]))


;; data functions

(defn parse-inputs [input]
  (map js/parseFloat (str/split input ",")))

(defn input-valid? [pt-str]
   (let [parsed (parse-inputs pt-str)]
      (= 2 (count parsed))
      (every? #(not (js/isNaN %)) parsed))))

(defn dist [[x1 y1 x2 y2]]
  (let [dx (.abs js/Math (- x1 x2))
        dy (.abs js/Math (- y1 y2))]
    [(.sqrt js/Math (+ (* dx dx) (* dy dy)))]))

(defn mdpt [[x1 y1 x2 y2]]
  [(/ (+ x1 x2) 2) (/ (+ y1 y2) 2)])

(defn slope [[x1 y1 x2 y2]]
  [(/ (- y1 y2) (- x1 x2))])

(defn value-of [f pt1-str pt2-str]
 (->> [pt1-str pt2-str]
     (map parse-inputs)
     (map #(pprint/cl-format nil "~,2f" %))
     (str/join ", ")))

;; ui functions

(defn text-input [place-holder value-atom]
  (fn []  [:input {:placeholder place-holder
                   :type "text"
                   :on-change #(reset! value-atom (-> % .-target .-value))}] ))

(defn invalid-input []
  [:h3.invalid-input.center "Enter a valid input to see the answer."])

(defn answer [pt1-str pt2-str]
   [:tr [:td "Distance"]       [:td (value-of dist pt1-str pt2-str)]]
   [:tr [:td "Midpoint"]       [:td (str "(" (value-of mdpt pt1-str pt2-str) ")")]]
   [:tr [:td "Slope"]          [:td (value-of slope pt1-str pt2-str)]]])

(defn answer-container [pt1-atom pt2-atom]
  (fn []
    (if (every? input-valid? [@pt1-atom @pt2-atom])
      [answer @pt1-atom @pt2-atom]

(defn container []
 (let [pt1 (r/atom "") pt2 (r/atom "")]
   (fn []
     [:div [text-input "x, y" pt1]
           [text-input "x, y" pt2]
           [answer-container pt1 pt2]])))

(r/render-component [container]
       (. js/document (getElementById "content")))

Here is a screen shot, if you are interested.

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.