ali-lunchy / script.js
bibekyess's picture
Deactivate weekend blocking for debugging
83ba68a
function shuffle(array, seed) { // <-- ADDED ARGUMENT
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(random(seed) * m--); // <-- MODIFIED LINE
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
++seed // <-- ADDED LINE
}
return array;
}
function random(seed) {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
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, seed) {
// Generate three random indices based on the seed
randomRestaurants = shuffle(restaurants, seed);
return randomRestaurants.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 seed = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate(); // Create a seed from the date
console.log('Random seed per day: ', seed);
const randomRestaurants = getRandomRestaurants(restaurants, seed);
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;