Menu
CoddyTech

Borrowing System

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 58 of 65.

challenge icon

Challenge

Medium

Move the lending into the library. Keep everything you wrote in the previous steps; only library.gd changes.

Add three methods to Library:

  1. find_book(isbn: String) -> Book returns the book with that ISBN, or null when there is none.
  2. find_user(user_id: String) -> User returns the user with that id, or null.
  3. borrow_book(isbn: String, user_id: String) -> String lends a book and returns a message. Check in this order:
    • no book with that ISBN: return Book not found
    • no user with that id: return User not found
    • the book is not available: return Book is not available
    • otherwise set the book's available to false and its borrower_id to the user id, append the ISBN to the user's borrowed_isbns and return Book borrowed successfully

The supplied code replaces lend with borrow ISBN|ID, which prints the message, and adds loans ID (the titles a user borrowed) and holder ISBN (who has a book). Both use your find_book() and find_user(). For this input:

Community
book Dune|Frank Herbert|111
user U001|Alice
user U002|Bob
borrow 999|U001
borrow 111|U999
borrow 111|U001
borrow 111|U002
holder 111
loans U001

the output is:

Book not found
User not found
Book borrowed successfully
Book is not available
Dune is borrowed by Alice
Alice has borrowed:
- Dune

Your code goes in book.gd, user.gd and library.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var library := Library.new(OS.read_string_from_stdin())
	var line := OS.read_string_from_stdin()
	while line != "":
		var parts := line.split(" ", true, 1)
		var fields: PackedStringArray = parts[1].split("|") if parts.size() > 1 else PackedStringArray()
		match parts[0]:
			"book":
				library.add_book(Book.new(fields[0], fields[1], fields[2]))
			"user":
				library.add_user(User.new(fields[0], fields[1]))
			"borrow":
				print(library.borrow_book(fields[0], fields[1]))
			"loans":
				var reader: User = library.find_user(fields[0])
				print(reader.user_name, " has borrowed:")
				for isbn in reader.borrowed_isbns:
					print("- ", library.find_book(isbn).title)
			"holder":
				var book: Book = library.find_book(fields[0])
				if book.available:
					print(book.title, " is on the shelf")
				else:
					print(book.title, " is borrowed by ", library.find_user(book.borrower_id).user_name)
			"books":
				for book in library.books:
					print(book)
			"users":
				for user in library.users:
					print(user)
			"show":
				print(library)
		line = OS.read_string_from_stdin()

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler