Sfoglia il codice sorgente

5.13: using function overloads.

Frederic G. MARAND 5 anni fa
parent
commit
407bdac6d3
1 ha cambiato i file con 39 aggiunte e 1 eliminazioni
  1. 39 1
      app/app.ts

+ 39 - 1
app/app.ts

@@ -111,6 +111,37 @@ function LogBookTitles(titles: string[]): void {
   }
 }
 
+// Note: no implementation.
+function GetTitles(author: string): string[];
+function GetTitles(available: boolean): string[];
+// Now an implementation:
+function GetTitles(bookProperty: any): string[] {
+  const allBooks = GetAllBooks();
+
+  const foundTitles: Array<string> = [];
+  if (typeof bookProperty == 'string') {
+    //  get books by author, add to foundTitles
+    for (let book of allBooks) {
+      if (book.author === bookProperty) {
+        foundTitles.push(book.title);
+      }
+    }
+  }
+  else if (typeof bookProperty === 'boolean') {
+    // get available books, add to foundTitles
+    for (let book of allBooks) {
+      if (book.available === bookProperty) {
+        foundTitles.push(book.title);
+      }
+    }
+  }
+  else {
+    throw new Error('Invalid property type: ' + typeof bookProperty);
+  }
+
+  return foundTitles;
+}
+
 //******************************************************************************
 function defaultParamsDemo() {
   CreateCustomer('Michelle');
@@ -163,8 +194,15 @@ function restParamsDemo() {
   myBooks.forEach(title => console.log(title);
 }
 
+function overloadDemo() {
+  console.log(GetTitles(true));
+  console.log(GetTitles('Herman Melville'));
+  // No: there is no function signature matching the next call.
+  // GetTitles(42);
+}
 
 // defaultParamsDemo();
 // functionTypeDemos();
 // functionCallDefaultParamsDemo();
-restParamsDemo();
+// restParamsDemo();
+overloadDemo();