CodingNic

Practical Challenges

Warm-Up Challenges

Practical Challenges 40 min read

Warm-Up Challenges

Objectives

This chapter introduces no new concepts. Each challenge below uses only things already taught in this course. Read the problem, work the example by hand, then write code that reproduces it exactly.

Challenge 1: FizzBuzz

Write a function fizzBuzz(n) that returns an array of strings for every number from 1 to n. For multiples of 3, use "Fizz" instead of the number. For multiples of 5, use "Buzz". For multiples of both 3 and 5, use "FizzBuzz". Otherwise, use the number itself, as a string.

Example:

javascript
fizzBuzz(15);
// ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]

Hint: check divisibility by both 3 and 5 (or, equivalently, by 15) before checking either one alone, otherwise a number like 15 will hit your 3 check and stop there.

Challenge 2: Reverse a String

Write a function reverseString(str) that returns str with its characters in reverse order.

Example:

javascript
reverseString("hello");      // "olleh"
reverseString("JavaScript"); // "tpircSavaJ"

Constraint: don’t reach for a built-in method that does this in one call, even if you’ve seen one mentioned elsewhere. Build the result yourself.

Hint: for...of works on strings too, not just arrays (Module 5 mentioned this). Loop over the string one character at a time, and think about which side of your result string each new character should go on.

Challenge 3: Find the Largest Number

Write a function largest(nums) that returns the largest number in an array. Assume the array always has at least one number.

Example:

javascript
largest([4, 19, 2, 77, 5]); // 77

Hint: this is a one-line .reduce() if you set it up right. What should the starting value be?

Challenge 4: Is It a Palindrome?

Write a function isPalindrome(str) that returns true if str reads the same forwards and backwards, and false otherwise. Case matters for this version, "Level" and "level" are different strings.

Example:

javascript
isPalindrome("level");   // true
isPalindrome("hello");   // false
isPalindrome("racecar"); // true

Hint: you already have a function from this lesson that does most of the work. A string is a palindrome exactly when it equals its own reverse.

Challenge 5: Count the Vowels

Write a function countVowels(str) that returns how many vowels (a, e, i, o, u, either case) appear in str.

Example:

javascript
countVowels("JavaScript"); // 3
countVowels("rhythm");     // 0

Hint: a regular expression with the g flag and .match() returns every match as an array, and null if there are none. Module 6 covered both.

Recap

Five small problems, each solvable with a single technique from earlier in the course, but without being told which one. That’s the whole point of this lesson: the thinking, not the syntax.

Next lesson: intermediate challenges, where problems start needing two or three techniques working together.