Prechádzať zdrojové kódy

4.6: using enums and arrays.

Frederic G. MARAND 5 rokov pred
rodič
commit
a95c03379e
1 zmenil súbory, kde vykonal 26 pridanie a 32 odobranie
  1. 26 32
      app/app.ts

+ 26 - 32
app/app.ts

@@ -3,57 +3,31 @@ enum Category {
   Poetry,        // 1
   Fiction,       // 2
 }
-enum Category2 {
-  Biography = 1, // 1
-  Poetry,        // 2
-  Fiction,       // 3
-}
-enum Category3 {
-  Biography = 1, // 1
-  Poetry = 5,    // 5
-  Fiction = 0,   // 0
-}
-
-let favoriteCategory: Category = Category.Fiction;
-console.log(favoriteCategory, Category[favoriteCategory], Category['Fiction'], Category[Category['Fiction']], Category);
-
-let strArray1: string[] = ['a', 'strings', 'array'];
-// "Generics" syntax.
-let strArray2: Array<string> = ['another'];
-
-// A plain Array wouldn't work: in this case Array is the TS generic, not the
-// JS builtin.
-let mixedArray1: Array<any> = [42, true, 'banana'];
-let mixedArray2: any[] = [42, true, 'banana'];
-let mixedArray3: (number|boolean|string)[] = [42, true, 'banana'];
-let mixedArray4 = [42, true, 'banana'];
-
-let myTuple: [number, string] = [25, 'truck'];
-let [firstElement, secondElement] = myTuple;
-myTuple[2] = 'book';
-// But not: myTuple[0] = 'book';
-// Nor: myTuple[2] = {}
 
 function GetAllBooks() {
   let books = [
     {
       author: 'James Joyce',
       available: true,
+      category: Category.Fiction,
       title: 'Ulysses',
     },
     {
       author: 'Ernest Hemingway',
       available: false,
+      category: Category.Fiction,
       title: 'A farewall to arms',
     },
     {
       author: 'Maya Angelou',
       available: true,
+      category: Category.Poetry,
       title: 'I know why the caged bird sings',
     },
     {
       author: 'Herman Melville',
       available: true,
+      category: Category.Fiction,
       title: 'Moby Dick',
     }
   ];
@@ -76,5 +50,25 @@ function LogFirstAvailable(books): void {
   console.log(`First available: ${firstAvailable}.`);
 }
 
-const allBooks = GetAllBooks();
-LogFirstAvailable(allBooks);
+function GetBookTitlesByCategory(categoryFilter: Category): Array<string> {
+  console.log(`Getting books in category: ${Category[categoryFilter]}.`);
+
+  const allBooks = GetAllBooks();
+  const filteredTitles: string[] = [];
+
+  for (let currentBook of allBooks) {
+    if (currentBook.category === categoryFilter) {
+      filteredTitles.push(currentBook.title);
+    }
+  }
+  return filteredTitles;
+}
+
+function LogBookTitles(titles: string[]): void {
+  for (let title of titles) {
+    console.log(title);
+  }
+}
+
+const poetryBooks = GetBookTitlesByCategory(Category.Poetry);
+LogBookTitles(poetryBooks);