Created
August 25, 2016 14:53
-
-
Save lispyclouds/f58ccc4b21e8005d04eafda8fc7fff03 to your computer and use it in GitHub Desktop.
The Bike Rental Code
This file contains 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
(ns bikes.core | |
(:gen-class) | |
(:require [clj-time.core :as t])) | |
(defrecord Bike [model price id]) | |
(defrecord Store [bikes currentRentals rentHistory]) | |
(defrecord Rental [bikeId rentedOn returnedOn rent]) | |
(defn find-rental-for-bike | |
[store bike] | |
(first (filter (fn [history] (= (.id bike) (.bikeId history))) (.currentRentals store)))) | |
(defn get-bike | |
[allBikes bikeId] | |
(first (filter (fn [bike] (= (.id bike) bikeId)) allBikes))) | |
(defn do-rent | |
[store bike] | |
(let [otherBikes (filter (fn [b] (not= b bike)) (.bikes store)) | |
newRentals (conj (.currentRentals store) (Rental. (.id bike) (t/now) nil 0))] | |
(Store. otherBikes newRentals (.rentHistory store)))) | |
(defn find-cost | |
[bike rentedOn returnedOn] | |
(* (t/in-days (t/interval rentedOn returnedOn)) (.price bike))) | |
(defn do-return | |
[store bike] | |
(let [rental (find-rental-for-bike store bike) | |
returnDate (t/now) | |
returnedRental (Rental. (.bikeId rental) (.rentedOn rental) returnDate (find-cost bike (.rentedOn rental) returnDate)) | |
newCurrentRentals (filter (fn [r] (not= r rental)) (.currentRentals store)) | |
newBikes (conj (.bikes store) (first (filter (fn [rental] (= (.bikeId rental) (.id bike))) (.currentRentals store)))) | |
newHistory (conj (.rentHistory store) returnedRental)] | |
(Store. newBikes newCurrentRentals newHistory))) | |
(defn -main | |
[& args] | |
(let [bikes [(Bike. "Thunderbird 350" 1000 1) | |
(Bike. "Classic 500" 900 2) | |
(Bike. "Himalayan" 1000 3)] | |
store (Store. bikes [] []) | |
bike (get-bike bikes 1) | |
store1 (do-rent store bike) | |
bike2 (get-bike bikes 2) | |
store2 (do-rent store1 bike2) | |
store3 (do-return store2 bike2) | |
store4 (do-return store3 bike)] | |
(do (println store1) | |
(println store2) | |
(println store3) | |
(println store4)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment