[2015-01-12] Challenge #197 [Easy] ISBN ValidatorThe challenge is to validate 10-digit ISBN numbers using the check digit. | (ns daily.easy-197
(:require
[dommy.core :refer-macros [sel1]]
[reagent.core :as reagent :refer [atom]])) |
Convert a numeral character into an integer. In this case, it also works with the Roman numeral "X". Solution | (defn char-to-num
[chr]
(if (= chr \X)
10
(js/parseInt chr))) |
The magic function here is The threading macro | (defn validate-isbn-10
[input]
(as-> input $ ;; bind `$` to the return value of the last function
(filter #(not= \- %) $)
(map char-to-num $) ;; convert the sequence of characters into one of integers
(map-indexed #(* (- 10 %1) %2) $) ;; multiply each integer by its "weight"
(reduce + $) ;; sum the integers
(mod $ 11)
(= 0 $))) |
ResultYou can try it out with one input string at a time using the following field. | (defn single-input []
(let [value (atom "0-3453-0256-7")]
(fn []
[:div
[:p "Input: "
[:input {:type "text" :value @value
:on-change #(reset! value (-> % .-target .-value))}]
[:p "Output: " (str (validate-isbn-10 @value))]]]))) |
(reagent/render-component [single-input] (sel1 :#single-input)) | |