Menu
CoddyTech

Search Functionality

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

challenge icon

Challenge

Medium

Add a title search. Keep everything you wrote in the previous steps; only library.gd changes.

Write search_by_title(text: String) -> Array[Book] in Library. It returns every book whose title contains text, in the order of books:

  • The search ignores upper and lower case: GREAT finds The Great Gatsby.
  • Part of a title is enough: great finds Great Expectations too.
  • An empty text returns every book. Check this case first: in GDScript "" in "Dune" is false.
  • Borrowed books are found like any other book.

The supplied code adds the command search TEXT, which prints how many books were found and one line per book. For this input:

Community
book The Great Gatsby|F. Scott Fitzgerald|123456
book To Kill a Mockingbird|Harper Lee|789012
book Great Expectations|Charles Dickens|345678
search great
search zzz

the output is:

Results for 'great': 2
- The Great Gatsby by F. Scott Fitzgerald
- Great Expectations by Charles Dickens
Results for 'zzz': 0

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]))
			"search":
				var term: String = parts[1] if parts.size() > 1 else ""
				var found: Array = library.search_by_title(term)
				print("Results for '%s': %d" % [term, found.size()])
				for book in found:
					print("- ", book.title, " by ", book.author)
			"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