My JavaScriptmas Journey š
Hi guys!
Iām starting by saying that this is my first article on a blog. So instead of just challenging myself on my JavaScript skills, Iām also challenging myself on my writing as well.
As you can already see from the title, this is about my adventure with the JavaScriptmas Challenge from Scrimba.
Initially I thought that it will be just a boring challenge with basic questions, not an entire list of little games. It was a lot of fun, āwtf is thisā and āomg, itās workingā. Every day I was looking forward to the guys from Scrimba posting their solution after the challenge, to see how I can improve my code.
My favorite ones: Candies (of course, who donāt like candies), Sort by length (I didnāt know until I did this one how to properly use the sort()), Fibonacci Numbers (old, but gold) and the Carousel.
Thereās my GitHub link to the solutions š
- Candies
function candies(children, candy) {
return Math.floor(candy / children) * children;
}
- Deposit Profit
function depositProfit(deposit, rate, threshold) {
let sum = deposit;
let years = 0; while (sum < threshold) {
sum = sum + (sum * 20) / 100;
years++;
}
return years;
}
- Chunky Monkey
function chunkyMonkey(values, size) {
return [[...values.slice(0, size)], [...values.slice(size, values.length)]];
}
- Century from year
function centuryFromYear(num) {
return Math.ceil(num / 100);
}
- Reverse a string
function reverseAString(str) {
return str.split("").reverse().join("");
}
- Sort by length
function sortByLength(strs) {
return strs.sort((a, b) => a.length - b.length);
}
- Count vowel consonant
function countVowelConsonant(str) {
const vowels = ["a", "e", "i", "o", "u"];
const chars = str.split("");
return (total = chars.reduce((acc, char) => {
if (vowels.includes(char)) {
return acc + 1;
}
return acc + 2;
}, 0));
}
- Rolling dice
const dice = document.querySelector(".dice");
const dots = document.querySelector(".dots");
const dotsClasses = ["dot", "dot2", "dot3", "dot4", "dot5", "dot6"];
let lastDots = "dot";function rollDice() {
dots.classList.remove(lastDots);
const randomClass = dotsClasses[Math.floor(Math.random() * 5)];
if (randomClass === lastDots) return; lastDots = randomClass;
dots.classList.add(randomClass);
}dice.addEventListener("click", rollDice);
- Sum Odd Fibonacci Numbers
function sumOddFibonacciNumbers(num) {
let sum = 0;
let previous = 0;
let current = 1;
while (current <= num) {
if (current % 2 === 1) {
sum += current;
}
const nextCurrent = cu;
}
return sum;
}
- Adjacent Elements Product
function adjacentElementsProduct(nums) {
let largestProduct = nums[0] * nums[1];
for (let i = 1; i < nums.length - 1; i++) {
const adjacentProduct = nums[i] * nums[i + 1]; if (largestProduct < adjacentProduct) {
largestProduct = adjacentProduct;
}
}
return largestProduct;
}
- Avoid Obstacles
function avoidObstacles(nums) {
const largestNum = nums.sort((a, b) => a - b)[nums.length - 1];
for (let i = 1; i <= largestNum + 1; i++) {
if (nums.every((value) => value % i !== 0)) {
return i;
}
}
}
- Valid Time
function validTime(str) {
const [hours, minutes] = str.split(":");
if (parseInt(hours) > 23 || parseInt(hours) < 0) {
return false;
}
if (parseInt(minutes) > 59 || parseInt(minutes) < 0) {
return false;
}
return true;
}
- Extract Each Kht
function extractEachKth(nums, index) {
return nums.filter((value, i) => (i + 1) % index !== 0);
}
- Maximal Adjacent Difference
function arrayMaximalAdjacentDifference(nums) {
let maxDifference = 0;
for (let i = 0; i < nums.length - 1; i++) {
const absoluteDifference = Math.abs(nums[i] - nums[i + 1]);
if (maxDifference < absoluteDifference) {
maxDifference = absoluteDifference;
}
}
return maxDifference;
}
- JavaScript Carousel
const gallery = document.getElementsByClassName("gallery")[0];
const prevBtn = document.getElementsByClassName("previous")[0];
const nextBtn = document.getElementsByClassName("next")[0];
const galleryCardCount = document.getElementsByClassName("card").length;let currentGalleryXOffset = 0;
const endGalleryXOffset = (galleryCardCount - 1) * -220;prevBtn.addEventListener("click", galleryClickHandler);
nextBtn.addEventListener("click", galleryClickHandler);function galleryClickHandler(event) {
let targetBtn = event.target.className;
if (targetBtn == "previous" && currentGalleryXOffset < 0) {
currentGalleryXOffset += 220;
} else if (targetBtn == "next" && currentGalleryXOffset > endGalleryXOffset) {
currentGalleryXOffset -= 220;
} if (currentGalleryXOffset == 0) {
prevBtn.style.opacity = 0.3;
prevBtn.style.cursor = "default";
} else {
prevBtn.style.opacity = 1; //disabled
prevBtn.style.cursor = "pointer";
} if (currentGalleryXOffset == endGalleryXOffset) {
nextBtn.style.opacity = 0.3;
nextBtn.style.cursor = "default";
} else {
nextBtn.style.opacity = 1;
nextBtn.style.cursor = "pointer";
} gallery.style.transform = `translateX(${currentGalleryXOffset}px)`;
}
- Insert Dashes
function insertDashes(str) {
const words = str.split(" ");
const dashedWords = words.map((word) => {
const chars = word.split(""); return chars.join("-");
});
return dashedWords.join(" ");
}
- Different symbols naive
function differentSymbolsNaive(str) {
const chars = str.split("");
return new Set(chars).size;
D
- Array previous less
function arrayPreviousLess(nums) {
const previousLess = [];
for (let i = nums.length - 1; i >= 0; i--) {
for (let j = i; j >= 0; j--) {
if (nums[i] > nums[j]) {
previousLess.unshift(nums[j]);
break;
} else if (j === 0) {
previousLess.unshift(-1);
}
}
}
return previousLess;
}
- Alphabet Subsequence
function arrayPreviousLess(nums) {
const previousLess = [];
for (let i = nums.length - 1; i >= 0; i--) {
for (let j = i; j >= 0; j--) {
if (nums[i] > nums[j]) {
previousLess.unshift(nums[j]);
break;
} else if (j === 0) {
previousLess.unshift(-1);
}
}
}
return previousLess;
}
- Domain Type
function domainType(domains) {
const domainTypes = [];
for (let i = 0; i < domains.length; i++) {
const urlPieces = domains[i].split(".");
const domain = urlPieces[urlPieces.length - 1];
if (domain === "org") {
domainTypes.push("organization");
} else if (domain === "com") {
domainTypes.push("commercial");
} else if (domain === "net") {
domainTypes.push("network");
} else if (domain === "info") {
domainTypes.push("information");
}
}
return domainTypes;
}
- Sum of 2
function sumOfTwo(nums1, nums2, value) {
const longerArray = nums1.length > nums2.length ? nums1 : nums2;
const shorterArray = nums1.length > nums2.length ? nums2 : nums1;
let isSum = 0;
longerArray.forEach((item) => {
shorterArray.forEach((item2) => {
if (item + item2 === value) isSum = isSum + 1;
});
});
return isSum != 0;
}
- Extract Matrix Column
function extractMatrixColumn(matrix, column) {
return matrix.map((row) => row[column]);
}
- Social media input challenge
let textArea = document.getElementById("string");
const button = document.querySelector("#btn");
function addDisableClass() {
button.classList.add("buttonDisabled");
}
function removeDisableClass() {
button.classList.remove("buttonDisabled");
}
function showText() {
let counterDisplay = document.getElementById("counterFooter");
let numberChars = textArea.value.length - 1;
counterDisplay.innerHTML = `${140 - numberChars}/140`;
if (numberChars > 140) {
button.disabled = true;
addDisableClass();
counterDisplay.style.color = "red";
} else if (numberChars >= 120 && numberChars <= 140) {
counterDisplay.style.color = "red";
} else {
button.disabled = false;
removeDisableClass();
counterDisplay.style.color = "white";
}
}
textArea.addEventListener("keydown", function (event) {
showText();
});
- Test Your Agility
var pushed = false;
var targetInt;
var spinningElem = document.getElementById("spinning");
document
.getElementById("buttonPressed")
.addEventListener("click", buttonPressed);
function buttonPressed() {
pushed = true;
}
function setTargetInt() {
var targetElem = document.getElementById("targetNum");
targetInt = Math.floor(Math.random() * 101);
targetElem.innerHTML = targetInt;
}
const sleep = (milliseconds) => {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
};
const spin = async () => {
let i = 0;
while (i < 100 && !pushed) {
await sleep(250);
++i;
spinningElem.innerHTML = i;
}
stop(i);
};
function stop(i) {
var result = document.getElementById("result");
if (i !== targetInt) {
result.innerHTML = `Oh no! you lose off by ${Math.abs(targetInt - i)}`;
} else {
result.innerHTML = `DANG DANG DANG YOU GOT IT CHAMP`;
}
}
setTargetInt();
spin();
Hereās a list with all my Scrimba solutions:
#Scrimba #JavaScriptmas