Skip to content

Commit

Permalink
Merge pull request #277 from avidrucker/fix-nil-circle-bug
Browse files Browse the repository at this point in the history
fix missing nil arg, neg arg err msgs
  • Loading branch information
daveliepmann committed Nov 26, 2023
2 parents 8ca06d5 + fd75cda commit 482411d
Showing 1 changed file with 44 additions and 5 deletions.
49 changes: 44 additions & 5 deletions shapes/src/shapes/core.cljs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
(ns shapes.core)
(ns shapes.core
(:require [clojure.string :as string]))

;; TODO add spec annotations!
;; TODO re-implement this mess using a transform matrix
Expand Down Expand Up @@ -38,23 +39,57 @@

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; helpers for param checks

(defn type-to-name
"Return a string representation of the type indicated by the symbol `thing`."
[thing]
(cond
(string? thing) "string"
(number? thing) "number"
(list? thing) "list"
(vector? thing) "vector"
(keyword? thing) "keyword"
(map? thing) "map"
(string/includes? (str thing) "function") "function"
:else thing))

(defn assert-number [message x]
(if (js/isNaN x)
(if (nil? x)
(throw (js/Error. message))
(js/parseFloat x)))
(if (js/isNaN x)
(throw (js/Error. message))
(js/parseFloat x))))

(defn assert-number-range [message x-min x-max x]
(let [x-parsed (assert-number message x)]
(if (<= x-min x-parsed x-max)
x-parsed
(throw (js/Error. message)))))

(defn assert-positive [message x]
(let [x-parsed (assert-number message x)]
(if (pos? x)
x-parsed
(throw (js/Error. message)))))

(defn say-why-not-num
;; note: This function still does not gracefully handle functions as bad-input, e.g (circle odd?)
[fname bad-input]
(if (nil? bad-input)
(str " The function `" fname "` can't use `nil`"
" because `nil` is not a number.")
(str " The function `" fname "` can't use '" bad-input
"' because '" bad-input "' is a " (type-to-name bad-input) ".")))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; basic types

(defn circle
"Returns a circle of `radius`."
[radius]
(assert-number "radius must be a number!" radius)
(assert-number (str "Argument `radius` has to be a number."
(say-why-not-num "circle" radius)) radius)
(assert-positive (str "Argument `radius` has to be a positive number."
" The function `circle` can't use '" radius
"' because it is not positive.") radius)
(map->Shape {:kind :circle
:r radius
:cx radius
Expand Down Expand Up @@ -92,7 +127,11 @@
(defn square
"Returns a square of dimension `side`."
[side]
(assert-number "side must be a number!" side)
(assert-number (str "Argument `side` has to be a number."
(say-why-not-num "square" side)) side)
(assert-positive (str "Argument `side` has to be a positive number."
" The function `square` can't use '" side
"' because it is not positive.") side)
(rectangle side side))

(defn text
Expand Down

0 comments on commit 482411d

Please sign in to comment.