forked from Clojure-Developer/Clojure-Developer-2024-06
-
Notifications
You must be signed in to change notification settings - Fork 6
homework 06 #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
m2608
wants to merge
2
commits into
Clojure-Developer:main
Choose a base branch
from
m2608:hw06
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
homework 06 #5
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,6 @@ | ||
| (ns otus-06.homework) | ||
| (ns otus-06.homework | ||
| (:require [clojure.string :as str] | ||
| [clojure.java.io :as io])) | ||
|
|
||
| ;; Загрузить данные из трех файлов на диске. | ||
| ;; Эти данные сформируют вашу базу данных о продажах. | ||
|
|
@@ -94,3 +96,233 @@ | |
|
|
||
|
|
||
| ;; Файлы находятся в папке otus-06/resources/homework | ||
|
|
||
| ; Файлы таблиц и соответствующие им описания схем. | ||
| (def db-description | ||
| {:customers | ||
| {:path "homework/cust.txt" | ||
| :schema "<custID, name, address, phoneNumber>"} | ||
| :products | ||
| {:path "homework/prod.txt" | ||
| :schema "<prodID, itemDescription, unitCost>"} | ||
| :sales | ||
| {:path "homework/sales.txt" | ||
| :schema "<salesID, custID, prodID, itemCount>"}}) | ||
|
|
||
| (defn parse-schema | ||
| "Парсит схему таблицы, возвращает вектор из имён полей | ||
| или `nil` в случае ошибки." | ||
| [schema-line] | ||
| (when-let [m (re-matches #"^[<](.+)[>]$" schema-line)] | ||
| (mapv keyword (str/split (second m) #",[ ]*")))) | ||
|
|
||
| ; Парсим описания схем для удобства. | ||
| (def db | ||
| (->> db-description | ||
| (map (fn [[table {path :path schema :schema}]] | ||
| [table {:path path :schema (parse-schema schema)}])) | ||
| (into {}))) | ||
|
|
||
| ; Разделитель столбцов. | ||
| (def delimiter #"[|]") | ||
|
|
||
| (defn autocoerce | ||
| "Пробует привести значение последовательно к `Integer` и `BigDecimal`. | ||
| Если не получается, возвращает значение как есть." | ||
| [value] | ||
| (try (Integer. value) | ||
| (catch NumberFormatException _ | ||
| (try (BigDecimal. value) | ||
| (catch NumberFormatException _ value))))) | ||
|
|
||
| (defn parse-row | ||
| "Парсит строку по указанной схеме, возвращает мапу." | ||
| [schema line] | ||
| (zipmap schema (map autocoerce (str/split line delimiter)))) | ||
|
|
||
| (defn symb-line | ||
| "Возвращает строку, состоящую из `n` указанных символов." | ||
| [s n] | ||
| (apply str (repeat n s))) | ||
|
|
||
| ; Возвращает строку дефисов. | ||
| (def dash-line (partial symb-line \-)) | ||
|
|
||
| ; Возвращает строку пробелов. | ||
| (def spaces (partial symb-line \space)) | ||
|
|
||
| (defmulti pad | ||
| "Выполняет паддинг значения в зависимости от его типа." | ||
| (fn [value _] (class value))) | ||
|
|
||
| ; Для чисел производится выравнивание по правому краю. | ||
| (defmethod pad java.lang.Integer | ||
| [value padding] | ||
| (format (str "%" padding "d") value)) | ||
|
|
||
| (defmethod pad java.math.BigDecimal | ||
| [value padding] | ||
| (format (str "%" padding ".2f") value)) | ||
|
|
||
| ; Кейворды приводятся к строке и центрируются. | ||
| (defmethod pad clojure.lang.Keyword | ||
| [value padding] | ||
| (let [value (name value) | ||
| full (- padding (count value)) | ||
| pref (quot full 2) | ||
| post (- full pref)] | ||
| (str (spaces pref) value (spaces post)))) | ||
|
|
||
| ; Для остальных типов значений - выравнивание по левому краю. | ||
| (defmethod pad :default | ||
| [value padding] | ||
| (str value (spaces (- padding (count (str value)))))) | ||
|
|
||
| (defn table-row | ||
| "Возвращает текстовое представление строки таблицы. Поля выводятся в | ||
| порядке, заданным в векторе `schema`. Ширина каждого поля задается в мапе `widths`." | ||
| [schema widths row] | ||
| (str "| " (str/join " | " (map (fn [col] (pad (row col) (widths col))) schema)) " |")) | ||
|
|
||
| (defn table-header | ||
| "Возвращает текстовое представление заголовка таблицы." | ||
| [schema widths] | ||
| (str "| " (str/join " | " (map #(pad % (widths %)) schema)) " |")) | ||
|
|
||
| (defn table-separator | ||
| "Возвращает декоративную строку, отделяющую заголовок таблицы от её содержимого." | ||
| [schema widths] | ||
| (str "+ " (str/join " + " (map (comp dash-line widths) schema)) " +")) | ||
|
|
||
| (defn get-max-widths | ||
| "Считает максимальную ширину для всех колонок из списка строк (включая заголовок). | ||
| Возвращает мапу, где ключами будут названия колонок." | ||
| [schema rows] | ||
| (->> schema | ||
| (map (fn [col] | ||
| [col (apply max | ||
| (count (name col)) | ||
| (map (comp count str col) rows))])) | ||
| (into {}))) | ||
|
|
||
| (defn select | ||
| "Выбирает из таблицы строки, для которых фильтрующая функция вернёт истину." | ||
| [db table-name filter-fn] | ||
| (->> (db table-name) | ||
| :path | ||
| io/resource | ||
| io/reader | ||
| line-seq | ||
| (map (partial parse-row (:schema (db table-name)))) | ||
| (filter filter-fn))) | ||
|
|
||
| (defn print-table | ||
| "Красиво печатает указанную таблицу." | ||
| [db table-name] | ||
| (let [schema (:schema (db table-name)) | ||
| rows (select db table-name (constantly true)) | ||
| widths (get-max-widths schema rows)] | ||
| (println (str "\n" (table-header schema widths) | ||
| "\n" (table-separator schema widths) | ||
| "\n" (str/join "\n" (map (partial table-row schema widths) rows)))))) | ||
|
|
||
| (defn print-sales-for-customer | ||
| "Печатает сумму, потраченную указанным покупателем на все покупки." | ||
| [db customer-name] | ||
| (if-let [customer (first (select db :customers #(= (:name %) customer-name)))] | ||
| (->> (select db :sales #(= (:custID %) (:custID customer))) | ||
| (map (fn [sale] | ||
| (let [product (first (select db :products #(= (:prodID %) (:prodID sale))))] | ||
| (* (:unitCost product) (:itemCount sale))))) | ||
| (reduce +) | ||
| (format "\n%s: $%.2f" customer-name) | ||
| println) | ||
| (println (format "\nCustomer \"%s\" not found." customer-name)))) | ||
|
|
||
| (defn print-sales-for-product | ||
| "Печатает количество проданных единиц указанного продукта." | ||
| [db product-name] | ||
| (if-let [product (first (select db :products #(= (:itemDescription %) product-name)))] | ||
| (->> (select db :sales #(= (:prodID %) (:prodID product))) | ||
| (map :itemCount) | ||
| (reduce +) | ||
| (format "\n%s: %d" product-name) | ||
| println) | ||
| (println (format "\nProduct \"%s\" not found." product-name)))) | ||
|
|
||
| (defn prompt | ||
| "Выводит приглашение и ожидает ввода пользователя." | ||
| [p] | ||
| (print p) | ||
| (flush) | ||
| (read-line)) | ||
|
|
||
| (defn get-menu | ||
| "Возвращает меню." | ||
| [db] | ||
| {:title "*** Sales Menu ***" | ||
| :exit "Exit" | ||
| :message "Enter option: " | ||
| :error "Unknown option number.\n" | ||
| :options | ||
| [{:name "Display Customer Table" :fn (partial print-table db :customers)} | ||
| {:name "Display Product Table" :fn (partial print-table db :products)} | ||
| {:name "Display Sales Table" :fn (partial print-table db :sales)} | ||
| {:name "Total Sales for Customer" :fn #(print-sales-for-customer db (prompt "Enter customer name: "))} | ||
| {:name "Total Count for Product" :fn #(print-sales-for-product db (prompt "Enter product name: "))}]}) | ||
|
|
||
| (defn print-menu | ||
| "Печатает на экран меню." | ||
| [menu] | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| (print (str/join "\n" | ||
| [(:title menu) | ||
| (dash-line (count (:title menu))) | ||
| (str/join "\n" (map-indexed | ||
| (fn [i {name :name}] | ||
| (format "%d. %s" (inc i) name)) | ||
| (:options menu))) | ||
| (format "%d. %s" (inc (count (:options menu))) (:exit menu)) | ||
| "" | ||
| (:message menu)])) | ||
| (flush)) | ||
|
|
||
| (defn read-number | ||
| "Читает число из стандартного ввода и парсит его, возвращает `nil` в случае | ||
| ошибки парсинга." | ||
| [] | ||
| (try (Integer/parseInt (read-line)) | ||
| (catch NumberFormatException _))) | ||
|
|
||
| (defn main-loop | ||
| "Показывает меню и выполняет действия в зависимости от выбора пользователя." | ||
| [menu] | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тот же самый дистракчеринг, что и выше, имхо был бы очень удобен |
||
| (loop [] | ||
| (print-menu menu) | ||
| (let [option (read-number)] | ||
| (cond | ||
| ;; Не удалось распарсить номер опции. Скорее всего, введено не число. | ||
| ;; Показываем текст ошибки. | ||
| (nil? option) | ||
| (do (println (:error menu)) | ||
| (recur)) | ||
|
|
||
| ;; Выбран один из пунктов меню. Вызваем функцию, которая определена в | ||
| ;; меню. | ||
| (<= 1 option (count (:options menu))) | ||
| (do | ||
| ((-> menu :options (nth (dec option)) :fn)) | ||
| (println) | ||
| (recur)) | ||
|
|
||
| ;; Выбрана опция выхода. Ничего не делаем, выходим. | ||
| (= option (inc (count (:options menu)))) | ||
| nil | ||
|
|
||
| ;; В остальных ситуациях выводим сообщение об ошибке. | ||
| :else | ||
| (do (println (:error menu)) | ||
| (recur)))))) | ||
|
|
||
| (defn -main | ||
| [] | ||
| (main-loop (get-menu db))) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вопрос вкуса, но имхо короче