File size: 2,599 Bytes
1960505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
async function fetchRestaurants() {
    const response = await fetch('restaurants.json');
    if (!response.ok) {
        throw new Error('Network response was not ok ' + response.statusText);
    }
    const data = await response.json();
    return data;
}

function getRandomRestaurants(restaurants) {
    // Fisher-Yates Shuffle Algorithm
    for (let i = restaurants.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [restaurants[i], restaurants[j]] = [restaurants[j], restaurants[i]];
    }
    return restaurants.slice(0, 3);
}

async function displayRestaurants() {
    const today = new Date();
    const day = today.getDay();

    // Format the date
    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    const formattedDate = today.toLocaleDateString(undefined, options);

    // Display the date
    document.getElementById('currentDate').innerText = `Today is ${formattedDate}`;

    // Only display suggestions on weekdays
    if (day === 0 || day === 6) {
        document.getElementById('restaurants').innerHTML = "No suggestions available today!";
        return;
    }

    const dateKey = today.toISOString().split('T')[0];
    let savedData = localStorage.getItem('restaurantSuggestions');

    if (savedData) {
        savedData = JSON.parse(savedData);
        if (savedData.date === dateKey) {
            document.getElementById('restaurants').innerHTML = savedData.restaurants.map(restaurant => 
                `<a href="${restaurant[1]}" target="_blank">${restaurant[0]}</a>`
            ).join('<br>');
            return;
        }
    }

    try {
        const restaurants = await fetchRestaurants();
        console.log('Fetched Restaurants:', restaurants); // Debugging: Print fetched restaurants
        const randomRestaurants = getRandomRestaurants(restaurants);
        console.log('Random Restaurants:', randomRestaurants); // Debugging: Print random restaurants
        document.getElementById('restaurants').innerHTML = randomRestaurants.map(restaurant => 
            `<a href="${restaurant[1]}" target="_blank">${restaurant[0]}</a>`
        ).join('<br>');

        const dataToSave = {
            date: dateKey,
            restaurants: randomRestaurants
        };

        localStorage.setItem('restaurantSuggestions', JSON.stringify(dataToSave));
    } catch (error) {
        console.error('Error fetching restaurants:', error);
        document.getElementById('restaurants').innerHTML = "Failed to load restaurant suggestions.";
    }
}

window.onload = displayRestaurants;