From f2d70137ea5cb9ef89595d945a24268ab95f906e Mon Sep 17 00:00:00 2001 From: Darbaz Ali Date: Sun, 2 May 2021 19:50:07 +0300 Subject: [PATCH] refactor getRandomItem func in toast notification project --- toast-notification/script.js | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/toast-notification/script.js b/toast-notification/script.js index ece1e00..96a8bec 100644 --- a/toast-notification/script.js +++ b/toast-notification/script.js @@ -1,35 +1,25 @@ const button = document.getElementById('button') const toasts = document.getElementById('toasts') -const messages = [ - 'Message One', - 'Message Two', - 'Message Three', - 'Message Four', -] +const messages = ['Message One', 'Message Two', 'Message Three', 'Message Four'] const types = ['info', 'success', 'error'] +// pick a random item from an array +const getRandomItem = (array) => array[Math.floor(Math.random() * array.length)] + button.addEventListener('click', () => createNotification()) function createNotification(message = null, type = null) { - const notif = document.createElement('div') - notif.classList.add('toast') - notif.classList.add(type ? type : getRandomType()) - - notif.innerText = message ? message : getRandomMessage() + const notif = document.createElement('div') + notif.classList.add('toast') + notif.classList.add(type ? type : getRandomItem(types)) - toasts.appendChild(notif) + notif.innerText = message ? message : getRandomItem(messages) - setTimeout(() => { - notif.remove() - }, 3000) -} + toasts.appendChild(notif) -function getRandomMessage() { - return messages[Math.floor(Math.random() * messages.length)] + setTimeout(() => { + notif.remove() + }, 3000) } - -function getRandomType() { - return types[Math.floor(Math.random() * types.length)] -} \ No newline at end of file