# Point utilities in ClojureScript and Reagent

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]))

(enable-console-print!)

;; data functions

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

(defn input-valid? [pt-str]
(let [parsed (parse-inputs pt-str)]
(and
(= 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)
(flatten)
(f)
(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."])

[: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)]]])

(fn []
(if (every? input-valid? [@pt1-atom @pt2-atom])
[invalid-input])))

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