DEV Community

Aishwarya Mali
Aishwarya Mali

Posted on

#JavaScriptmas 2023 Day 1 to 6

This is my first time participating in the #JavaScriptmas Challenge of Scrimba, and this is my take on its solutions.

What is #JavaScriptmas Challenge?

This is a FREE challenge hosted by Scrimba where you get a coding challenge related to JavaScript and CSS each day, starting from December 1st to December 24th. You can learn more about it here.

Day 1: Countdown to Christmas

Task

  • Get today's date (you only need the day).
  • Calculate remaining days.
  • Display remaining days in countdownDisplay.

Stretch Goals

  • Display hours, minutes and seconds.
const countdownDisplay = document.getElementById("countdown-display")
const timeLeft = document.getElementById("time-left")

function renderCountdown(){
    const christmas = 25
    const date = new Date()

    const todaysDate = date.getDate()
    const hours = date.getHours()
    const minutes = date.getMinutes()
    const seconds = date.getSeconds()

    const remainingDays = christmas - todaysDate

    countdownDisplay.textContent = remainingDays
    timeLeft.textContent = `${hours} hrs : ${minutes} mins : ${seconds} secs`
}

renderCountdown()
Enter fullscreen mode Exit fullscreen mode
  • First created a date variable which calls new Date() that returns a date object with the current date and time.
  • Based on that, retrieved today's date, hours, minutes, and seconds. Then calculated the remaining days with remainingDays = christmas - todaysDate
  • Finally, appended this information to the UI.

Check my scrim here.

Day 2: Style a Colorful Button

HTML

 <div class="container">
  <div class="button-border">
   <button type="button" class="button">
    Start Coding!
   </button>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.button-border{
    position: relative;
    background: linear-gradient(115deg, var(--grad-color1), var(--grad-color2), var(--grad-color3),var(--grad-color4),var(--grad-color5));
    padding: 2px 3px;
    text-align: center;
    transition: all 0.2s;
}

.button-border:hover{
    background: linear-gradient(-115deg, var(--grad-color1), var(--grad-color2), var(--grad-color3),var(--grad-color4),var(--grad-color5));
    transform: scale(1.1);
}

.button{
    display: block;
    color: var(--btn-color);
    background: var(--btn-bg);
    letter-spacing: 1px;
    padding: 20px 30px;
    border: none;
    font-family: 'Karla', sans-serif;
}

.button:hover{
    color: var(--btn-color-hover);
}
Enter fullscreen mode Exit fullscreen mode
  • The trick here was to give .button-border gradient background and then placing your button on top of it.

Check my scrim here.

Day 3: Divide Candy

Task

  • Find the total number of pieces of candy the children can eat.
  • Example:
    • Children: 3, Candies: 10
    • Each of the 3 children can eat 3 candies.
    • So the total number of candies that can be eaten
    • is 3*3 = 9. So the function calcTotalCandies should
    • log out 9.
function calcTotalCandies(children, candy) {
 const oneChildCanEat = Math.floor(candy/children) 
 const totalCandiesEaten = oneChildCanEat * children
 console.log(totalCandiesEaten)
}

calcTotalCandies(3, 10) // expected output: 9
calcTotalCandies(4, 20) // expected output: 20
calcTotalCandies(6, 25) // expected output: 24
Enter fullscreen mode Exit fullscreen mode
  • For this, first determined the number of candies one child can eat by using Math.floor(candy/children).
  • Next, multiplied this value by the total number of children to obtain the result.

Check my scrim here.

Day 4: AI Christmas Joke Generator

Task

  • Use AI to generate one-line Christmas Joke.
  • Use AI provider (openai / huggingface)
import { HfInference } from '@huggingface/inference'

const hf = new HfInference(process.env.HUGGING_FACE_API_KEY)
const model = "tiiuae/falcon-7b-instruct"

document.getElementById('window-container').addEventListener('click', async function () {

    const jokeResponse = await hf.textGeneration({
        model: model,
        inputs: 'Tell me a random one line Christmas joke.'
    }) 

    const joke = jokeResponse.generated_text.replace(/Tell me a random one line Christmas joke\./i, '');

    const jokeEl = document.getElementById('joke-display')
    jokeEl.textContent = joke
})

Enter fullscreen mode Exit fullscreen mode
  • This one was a bit tough. I used huggingface for this challenge. You can find the documentation here.
const jokeResponse = await hf.textGeneration({
    model: model,
    inputs: 'Tell me a random one line Christmas joke.'
})
Enter fullscreen mode Exit fullscreen mode
  • hf.textGeneration is a function from the Hugging Face library for generating text.
  • model represents the model used for text generation.
  • The inputs parameter is set to the prompt 'Tell me a random one line Christmas joke.'
  • So in short, this code is asking a model from Hugging Face to generate a random one-liner Christmas joke in response to the given prompt. The result, the generated joke, is stored in the variable jokeResponse.

Check my scrim here.

Day 5: Jeopardy Card Flip

HTML

<div class="card">
 <div class="card-inner">
  <div class="card-front">
   <h2>
    This now deprecated HTML tag, popular in the early days of 
    the internet, magically made text scroll across the screen 
   </h2>
  </div>
  <div class="card-back">
   <h2>What is the marquee tag</h2>
  </div>
 </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.card{
  perspective: 1000px;
  background-color: transparent;
  width: 400px;
  height: 250px;
}

.card h2{
  text-transform: uppercase;
  color: var(--font-color-main);
  padding: 20px
}

.card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.6s;
  transform-style: preserve-3d;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  background-color: var(--jeopardy-blue);
  border-radius: 10px;
}

.card:hover .card-inner {
  transform: rotateY(180deg);
}

.card-front, .card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.card-front, .card-back{
  display: flex;
  align-items: center;
}

.card-back{
  justify-content: center;
  transform: rotateY(180deg);
}
Enter fullscreen mode Exit fullscreen mode

Check my scrim here.

Day 6: Secret Santa

Task

  • Write a function to randomly assign each person in an array a "Secret Santa", who is someone else in the array.
  • No one should be assigned themselves as their own Secret Santa.

Stretch goals

  • Create a UI with a button to trigger your Secret Santa function and display the results.
const ssPairBtn = document.getElementById("ss-pairs")
const displayPairsEl = document.getElementById("display-pairs")

const people = ["Alice", "Bob", "Carly", "Dan", "Ed", "Ferdinand", "Ginny"]

ssPairBtn.addEventListener('click', function(){
    const secretSantaPairs = generateSecretSantaPairs(people)
    let list = ""
    Object.entries(secretSantaPairs).forEach(([name, pair])=>{
        list += `<li>${name} = ${pair}</li>`
    })
    displayPairsEl.innerHTML = list
})

function generateSecretSantaPairs(arr) {
    const secretSantaPairs={}
    const peopleCopy = [...arr]
    const shuffledArray = shuffle(peopleCopy)
    for(let i=0; i<arr.length; i++){
        if(arr[i] !== shuffledArray[i]){
            secretSantaPairs[arr[i]] = shuffledArray[i]
        } else {
            const temp = shuffledArray[i];
            shuffledArray[i] = shuffledArray[(i + 1) % arr.length];
            shuffledArray[(i + 1) % arr.length] = temp;
            secretSantaPairs[arr[i]] = shuffledArray[i];
        }
    }
    return secretSantaPairs
}

function shuffle(arr){
    return arr.sort(() => Math.random() - 0.5);
}
Enter fullscreen mode Exit fullscreen mode
  • For this challenge, first shuffled the original array using the shuffle function. Then, ensured that no one should be assigned themselves as their own Secret Santa.
  • If that condition isn't met, pairs are assigned.
  • Otherwise, a temporary variable (temp) stores the person at the current index (i) in the shuffled array.
  • The next two lines swap the person at index i with the person at the next index in a circular manner. This is done to avoid pairing someone with themselves.
  • The pair is then added to the secretSantaPairs object, where the original person is paired with the new person after the swap.
  • Finally, this function is called on the "Secret Santa Pairs" button click, and the pairs are appended to the UI.

Check my scrim here.

Would love to hear your thoughts. Stay tuned for the next iteration of this series.

Top comments (0)