Menu
Coddy logo textTech

Adding Books

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 43 of 65.

challenge icon

Challenge

Easy

Add the case "addBook". This case should:

  1. Create a new book object using the currentData parameter which holds the following properties:
    • title (string)
    • author (string)
    • year (string)
    • genre (string)
  2. Generate an id (use libraryData.books.length + 1)
  3. Set default values for: isRead, rating, borrowed, borrowedBy, borrowDate (like in the initial data)
  4. Add the new book to libraryData.books array
  5. Add the string Book added successfully! to the results array 

Try it yourself

// Initialize library data
const libraryData = {
    books: [
        {
            id: 1,
            title: "The Great Gatsby",
            author: "F. Scott Fitzgerald",
            year: 1925,
            genre: "Fiction",
            isRead: false,
            rating: 0,
            borrowed: false,
            borrowedBy: "",
            borrowDate: ""
        }
    ],
    readers: [
        {
            name: "John Smith",
            favoriteGenre: "Fiction",
        }
    ]
};

function manageLibrary(actions, data) {
    let results = [];
    
    for (let i = 0; i < actions.length; i++) {
        const currentAction = actions[i];
        const currentData = data[i];
        
        switch (currentAction) {
            case 'printBooks':
                results.push(libraryData.books);
                break;
            case 'printReaders':
                results.push(libraryData.readers);
                break;
            default:
                results.push("Invalid action!");
        }
    }
    
    return results;
}

All lessons in Logic & Flow