Menu
CoddyTech

添加放映场次

本课属于 Coddy JavaScript 学习旅程的“逻辑与流程”单元。第 62 课,共 65 课。

challenge icon

挑战

简单

在 switch 语句中添加一个新的测试用例:addScreening。

对于 addScreening,数据参数包含:

  • movieId(数字)
  • venueId(数字)
  • date(格式为 'YYYY-MM-DD' 的字符串)
  • time(格式为 'HH:MM:SS' 的字符串)

该函数应:

  1. 验证 festivalData 中是否存在具有指定 movieId 的电影,以及具有指定 venueId 的场馆。如果其中任何一个不存在,就将 "Movie or venue not found!" 添加到结果中
  2. 检查同一场馆、日期和时间是否没有放映场次。如果场次已存在,就将 "Screening already exists at this time!" 添加到结果中
  3. 创建一个新的放映场次对象,其中包含:
    • id:将放映场次数组的长度加 1 生成
    • 从数据中获取 movieId、venueId、date 和 time
    • availableSeats:设为场馆的容量
  4. 将该放映场次添加到 festivalData.screenings 数组中
  5. 将 Screening added successfully! 添加到结果数组中

亲手试试

const festivalData = {
	movies: [{
		id: 1,
		title: "Inception",
		director: "Christopher Nolan",
		year: 2010,
		mainGenre: "Sci-Fi",
		secondGenre: undefined,
		avgRating: 0,
		available: true
	}],
	venues: [{
		id: 1,
		name: "Main Theater",
		capacity: 200,
	}],
	screenings: [{
		id: 1,
		movieId: 1,
		venueId: 1,
		date: '2023-10-29',
		time: '13:35:00',
		availableSeats: 200
	}],
	tickets: new Set()
};

function manageFestival(actions, data) {
    let results = [];
    
    actions.forEach((action, index) => {
        const currentData = data[index];
        
        switch(action) {
            case "listMovies":
                results.push(festivalData.movies);
                break;
                
            case "listVenues":
                results.push(festivalData.venues);
                break;

            case "listTickets":
                results.push(festivalData.tickets);
                break;

            case "listScreenings":
                results.push(festivalData.screenings);
                break;

            case "addMovie":
                const newMovie = {
                    id: festivalData.movies.length + 1,
                    title: currentData.title,
                    director: currentData.director,
                    year: currentData.year,
                    mainGenre: currentData.mainGenre,
                    secondGenre: currentData.secondGenre,
                    avgRating: 0,
                    available: true
                };
                festivalData.movies.push(newMovie);
                results.push("Movie added successfully!");
                break;

            case "addVenue":
                const newVenue = {
                    id: festivalData.venues.length + 1,
                    name: currentData.name,
                    capacity: currentData.capacity,
                };
                festivalData.venues.push(newVenue);
                results.push("Venue added successfully!");
                break;


            default:
                results.push("Invalid action!");
        }
    });
    
    return results;
}

逻辑与流程中的所有课

自己练习: JavaScript 在线编译器