Scrimba: JavaScript Advent Calendar
Solutions for the Scrimba JavaScriptmas Challenge
Day 24: Test Your Agility!
var pushed = false //Has the stop button been pushed - false is default var targetInt; //The target number to stop the wheel on var spinningElem = document.getElementById('spinning'); //The spinning number const maxLoop = 10; const waitTime = 250; //event listener document.getElementById("buttonPressed").addEventListener("click", buttonPressed); //When the stop button is pushed function buttonPressed(){ pushed = true; } //set the target Int function setTargetInt(){ var targetElem = document.getElementById('targetNum'); targetInt=Math.floor(Math.random() * (maxLoop + 1)) targetElem.innerHTML = targetInt; } //sleep const const sleep = (milliseconds) => { return new Promise(resolve => setTimeout(resolve, milliseconds)) } var curr_spin=-1; //EDIT THIS FUNCTION const spin = async () => { var spinningElem = document.getElementById('spinning'); for(let spin=0; spin < maxLoop; spin++) { spinningElem.innerHTML = spin; console.log('spin:', spin, targetInt, curr_spin) if (!pushed) { // } else if (spin == targetInt) { console.log('Button pushed and won') var result = document.getElementById('result'); result.innerText = "WON!"; spin = maxLoop+1; } else { console.log('Buitton pushed but missed') spin = maxLoop+1; } await sleep(waitTime) } } //main setTargetInt(); spin();
Day 23: Social media input challenge
<html> <head> <link rel="stylesheet" href="index.css"> </head> <body> <div class="container"> <textarea type="text" id="tweet" placeholder="Type in the box"></textarea> <div id="counterFooter">140/140</div> <button id="btn"><h2>Tweet</h2></button> </div> <script src="index.js"></script> </body> </html>
body{ background-color: #023F6A; font-family: sans-serif; } .container{ display: flex; align-items: center; justify-content: center; flex-direction: column; } textarea{ width:50%; height: 30vh; background-color: rgb(21, 32, 43); color: #fff; border-radius:10px; } textarea::placeholder{ color:#fff; } #counterFooter { margin-top: 0.2rem; font-size:0.8rem; color: #fff; margin-left:30%; font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } button{ width:50%; background-color: rgb(29, 161, 242); border-radius: 10px; padding: 0 10%; } .tweetRed { color: red; } button h2{ color: #fff; } .buttonDisabled { opacity: .5; cursor: default; }
const counter = document.getElementById('counterFooter'); const button = document.getElementById('btn'); function updateState() { const nrOfChar = 140 - tweet.value.length; counter.innerText = nrOfChar + '/140'; (nrOfChar < 20) ? tweet.classList.add("tweetRed") : tweet.classList.remove("tweetRed"); (nrOfChar < 0) ? btn.classList.add("buttonDisabled") : btn.classList.remove("buttonDisabled"); } function handleKeyUp(event) { updateState() } tweet.addEventListener('keyup', handleKeyUp); updateState()
Day 22: Extract Matrix Column
function extractMatrixColumn(matrix, column) { let extracted = [] matrix.forEach( row => { extracted.push(row[column]) }) return extracted; }
function extractMatrixColumn(matrix, column) { return matrix.map( row => row[column]) }
Day 21: Sum of 2
function sumOfTwo(nums1, nums2, value) { let result = false; nums1.forEach( num1 => { nums2.forEach( num2 => { if ( (num1 + num2) === value) { result = true; } }) }) return result; }
Day 20: Domain Type
function domainType(domains) { map = { "org": "organization", "com": "commercial", "net": "network", "info": "information" } types=[] domains.forEach( (domain) => { last = domain.split('.').slice(-1)[0] types.push(map[last]) }) return types }
Day 19: Alpahabet Subsequence
function alphabetSubsequence(str) { chars = str.split("") result=true for(pos=1; pos<chars.length; pos++) { result = result && chars[pos-1] < chars[pos] } return result }
Day 18: Array previous less
function arrayPreviousLess(nums) { let result = []; let temp=[]; for(indx=0; indx < nums.length; indx++) { curr = nums[indx]; // Build array with previous values temp.push(curr) // Find previous values less than current value mins = temp.filter( (val) => val < curr) // Return value at most right max = (mins.length == 0) ? -1 : max = mins[mins.length-1]; result.push(max); } return result; }
Day 17: Different symbols naive
function differentSymbolsNaive(str) { m={}; n=0; str.split("").sort().forEach( (c) => { if (! (c in m)) n++; m[c]=1; }); return n }
Day 16: Insert dashes
function insertDashes(arr) { return arr.split(" ").map( part =>part.split("").join("-") ).join(" "); }
Day 15: Javascript Carousel
function getIndexOfCurrent(tags) { let result = -1; tags.forEach((node, indx) => { if (node.classList.contains('curr')) { result = indx; } }); return result; } function move(dir) { var tags = Array.prototype.slice.call( document.getElementsByClassName('card') ); let curr = getIndexOfCurrent(tags); if (dir === 'prev') { next = curr === 0 ? 0 : curr - 1; } if (dir === 'next') { next = curr === tags.length - 1 ? tags.length - 1 : curr + 1; } tags[curr].setAttribute('class', 'card last'); tags[next].setAttribute('class', 'card curr'); }
<html> <head> <link rel="stylesheet" href="index.css"> </head> <body> <div class="container"> <img src="previous.svg" class="previous" alt="previous image"> <div class="gallery-wrapper"> <div class="gallery"> <img class="card curr" src="presents.jpg" alt="Christmas Cookies"> <img class="card" src="cookies.jpg" alt="Christmas Cookies"> <img class="card" src="santa.jpg" alt="Christmas Cookies"> <img class="card" src="candycane.jpg" alt="Christmas Cookies"> <img class="card" src="reindeer.jpg" alt="Christmas Cookies"> </div> </div> <img src="next.svg" class="next" alt="next image"> </div> <script src="index.pack.js"></script> </body> </html>
/* Thanks to these fine individuals from Unsplash: https://unsplash.com/photos/AmzKuEnr1VY https://unsplash.com/photos/eDnJQL21amc https://unsplash.com/photos/LXy2DOOxESQ https://unsplash.com/photos/KBKHXjhVQVM https://unsplash.com/photos/PxM8aeJbzvk */ @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600&display=swap'); html, body { margin: 0; padding: 0; height: 100vh; font-family: 'Playfair Display'; display: grid; justify-content: center; } img { width: 200px; } .previous, .next { width: 35px; justify-self: center; align-self: center; cursor: pointer; } .previous { opacity: 0.3; } .container { display: grid; grid-template-columns: 20% 200px 20%; place-content: center; } .card { width: 100%; display: none; } .curr { display: block; } .curr { animation-duration: 5s; animation-name: slideIn; } .last { animation-duration: 2s; animation-name: slideOut; } @keyframes slideOut { from { opacity: 1; } to { opacity: 0; } } @keyframes slideIn { from { opacity: 0; } to { opacity: 1; } }
Day 14: Maximal Adjacent Difference
let result=0, max=0, val1=0, val2=0; for(pos=0; pos < nums.length; pos++) { [val1, val2 ] = [ nums[pos], nums[pos+1] ]; max = (val1 > val2) ? (val1 - val2) : (val2 - val1); if (max > result) { result = max; } } return result; }
Day 13: Extract Eacth Kth
function extractEachKth(nums, kth) { return nums.filter( (value, index) => (index+1) }
Day 12: Valid Time
Number.prototype.between = function(min, max) { return this > min && this < max; }; function validTime(str) { const parts = str.split(':') return parseInt(parts[0]).between(0,24) && parseInt(parts[1]).between(0,59); }
Day 11: Avoid Obstacles
function avoidObstacles(nums) { const sorted = nums.sort(); for(num=2; num <= sorted[nums.length-1]; num++) { match = nums.filter((val) => (val if (match.length === 0) { return num; } } }
Day 10: Adjacent Elements Product
function adjacentElementsProduct(nums) { let result = 0; for (i1 = 0; i1 < nums.length-1; ++i1) { const product=nums[i1]*nums[i1+1]; if (product > result) { result = product; } } return result; }
Day 09: Sum Odd Fibonacci Numbers
function sumOddFibonacciNumbers(num) { let fibPrev=1; let fib=0; let sum=0; while (fibPrev < num) { [ fibPrev, fib ] = [fib + fibPrev, fibPrev]; if (fib sum += fib; } } return sum; }
Day 08: Rolling Dice
<html> <head> <link rel="stylesheet" href="style.css"> <script src="index.pack.js"></script> </head> <body> <div class="dice"> <div class="dot dot_ dot2 dot_ dot4 dot5 dot6"></div> <div class="dot dot_ dot_ dot_ dot_ dot_ dot_"></div> <div class="dot dot_ dot_ dot3 dot4 dot5 dot6"></div> <div class="dot dot_ dot_ dot_ dot_ dot_ dot6"></div> <div class="dot dot1 dot_ dot3 dot_ dot5 dot_"></div> <div class="dot dot6"></div> <div class="dot dot_ dot_ dot3 dot4 dot5 dot6"></div> <div class="dot"></div> <div class="dot dot_ dot2 dot_ dot4 dot5 dot6"></div> </div> </body> </html>
function clear_dice() { document.querySelectorAll('.dot').forEach( (dot) => dot.style.visibility = "hidden") } function roll_dice() { const roll = 1 + Math.floor(Math.random() * 6); console.log(roll); clear_dice() document.querySelectorAll('.dot'+roll).forEach( (dot) => { dot.style.visibility = "visible" }) } clear_dice() document.getElementsByClassName('dice')[0].addEventListener('click', roll_dice)
body { background-color: #AEB8FE; display: flex; } .dice { width: 230px; height: 230px; border-radius: 10px; background-color: #EFE5DC; margin: 100px; display: grid; grid-template-columns: repeat(3, 40px); gap: 20px; grid-auto-rows: minmax(40px, 40px); } .dot { width: 40px; height: 40px; border-radius: 15px; background-color: black; margin: 35px; visibility: hidden } .dot1 { visibility: none; } .dot2 { visibility: none; } .dot3 { visibility: none; } .dot4 { visibility: none; } .dot5 { visibility: none; } .dot6 { visibility: none; }
Day 07: Count Vowel Consonant
function countVowelConsonant(str) { function reducer(s,c) { return s + ("aeiou".includes(c) ? 1 : 2) }; return str.split("").reduce(reducer, 0) }
Day 06: Sort By Length
function sortByLength(strs) { return strs.sort(function(arg1, arg2) { return arg1.length - arg2.length }) }
Day 05: Reverse String
function reverseAString(str) { return str.split("").reverse().join("") }
Day 04: Century From Year
function centuryFromYear(num) { return Math.floor((num + 99) / 100) }
Day 03: Chunky Monkey
function chunkyMonkey(values, size) { result = []; pos = 0; while (pos < values.length) { result.push(values.slice(pos, pos+size)); pos += size; } return result; }
Day 02: Deposit Profit
function depositProfit(deposit, rate, threshold) { let profit = deposit; let years = 0 while (profit < threshold) { profit += profit * 0.01 * rate; years++; } return years; }
Day 01: Candies
https://scrimba.com/learn/adventcalendar/note-at-0-00-coef0430d83cd2a72113bbf09
function candies(children, candy) { return children * Math.floor(candy / children)// write code here. }