|
15 | 15 | // --------------- |
16 | 16 | // pickFromArray(['a','b','c','d']) // maybe returns 'c' |
17 | 17 |
|
18 | | -// You don't need to change this function |
19 | | -function pickFromArray(choices) { |
20 | | - return choices[Math.floor(Math.random() * choices.length)]; |
21 | | -} |
22 | | - |
23 | 18 | // A list of quotes you can use in your app. |
24 | 19 | // DO NOT modify this array, otherwise the tests may break! |
25 | 20 | const quotes = [ |
@@ -491,3 +486,52 @@ const quotes = [ |
491 | 486 | ]; |
492 | 487 |
|
493 | 488 | // call pickFromArray with the quotes array to check you get a random quote |
| 489 | + |
| 490 | +// Function to pick a random quote |
| 491 | +function pickFromArray() { |
| 492 | + const quoteEl = document.getElementById("quote"); |
| 493 | + const authorEl = document.getElementById("author"); |
| 494 | + const randomIndex = Math.floor(Math.random() * quotes.length); |
| 495 | + |
| 496 | + quoteEl.textContent = `" ${quotes[randomIndex].quote} "`; |
| 497 | + authorEl.textContent = `-- ${quotes[randomIndex].author} --`; |
| 498 | + return randomIndex; |
| 499 | +} |
| 500 | + |
| 501 | +// Setup function for browser only |
| 502 | +function setupQuoteApp() { |
| 503 | + const button = document.getElementById("new-quote"); |
| 504 | + const autoplayCheckbox = document.getElementById("autoplay"); |
| 505 | + const autoplayStatus = document.getElementById("autoplay-status"); |
| 506 | + |
| 507 | + // Don't call pickFromArray here for Jest test |
| 508 | + if (typeof window !== "undefined" && window.document) { |
| 509 | + pickFromArray(); |
| 510 | + |
| 511 | + button.addEventListener("click", () => pickFromArray()); |
| 512 | + |
| 513 | + let autoplayInterval = null; |
| 514 | + autoplayCheckbox.addEventListener("change", () => { |
| 515 | + if (autoplayCheckbox.checked) { |
| 516 | + autoplayInterval = setInterval(pickFromArray, 5000); |
| 517 | + autoplayStatus.textContent = "Auto-play: ON"; |
| 518 | + autoplayStatus.style.color = "#4CAF50"; |
| 519 | + } else { |
| 520 | + clearInterval(autoplayInterval); |
| 521 | + autoplayInterval = null; |
| 522 | + autoplayStatus.textContent = "Auto-play: OFF"; |
| 523 | + autoplayStatus.style.color = "brown"; |
| 524 | + } |
| 525 | + }); |
| 526 | + } |
| 527 | +} |
| 528 | + |
| 529 | +// Only run setup in browser environment |
| 530 | +if (typeof window !== "undefined") { |
| 531 | + window.addEventListener("DOMContentLoaded", setupQuoteApp); |
| 532 | +} |
| 533 | + |
| 534 | +// Export function for Jest tests |
| 535 | +if (typeof module !== "undefined") { |
| 536 | + module.exports = pickFromArray; |
| 537 | +} |
0 commit comments