Welcome! These are some bonus puzzles to accompany Intro to JavaScript class. Please take a look at the puzzles, and work on one that looks challenging but not completely overwhelming. You can always reference the slides if you get stuck. Commit to spend at least 20 minutes trying to figure out a problem before you look at the answers. It helps you learn!
Why pay a fortune teller when you can just program your fortune yourself?
var jobTitle = 'web developer';
var home = 'sprawling beachfront treehouse';
var place = 'Costa Rica';
var hobby = 'play Scrabble';
var future = 'You will be a ' + jobTitle + ' living in a ' + home + ' in ' + place + '. For fun you will ' + hobby + '.'
console.log(future);
squareNumber
that will take one argument (a number), square that number, and return the result. It should also log a string like "The result of squaring the number 3 is 9." halfNumber
that will take one argument (a number), divide it by 2, and return the result. It should also log a string like "Half of 5 is 2.5.".percentOf
that will take two numbers, figure out what percent the first number represents of the second number, and return the result. It should also log a string like "2 is 50% of 4."areaOfCircle
that will take one argument (the radius), calculate the area based on that, and return the result. It should also log a string like "The area for a circle with radius 2 is 12.566370614359172."
function squareNumber(num) {
var squaredNumber = num * num;
console.log('The result of squaring the number ' + num + ' is ' + squaredNumber);
return squaredNumber;
}
squareNumber(3);
function halfOf(num) {
var half = num / 2;
console.log('Half of ' + num + ' is ' + half);
return half;
}
halfOf(5);
function percentOf(num1, num2) {
var percent = (num1/num2) * 100;
console.log(num1 + ' is ' + percent + '% of ' + num2);
return percent;
}
percentOf(5, 10);
function areaOfCircle(radius) {
var area = Math.PI * squareNumber(radius);
console.log('The area of circle with radius ' + radius + ' is ' + area);
return area;
}
areaOfCircle(2);
function doCrazyStuff(num) {
var half = halfOf(num);
var squared = squareNumber(half);
var area = areaOfCircle(squared);
var result = percentOf(squared, area);
}
doCrazyStuff(5);
If you feel comfortable with the other exercises, it's time to expand your knowledge! These puzzles involve manipulating strings; to try them out, you'll need to use some of the built-in JavaScript methods for strings. Methods are pre-written functions that are built into the language.
These questions are not as straightforward as the others. They challenge you to really think like a programmer. Really try to solve them before you peek at the answer.
Create a function called mixUp
. It should take in two strings, and return the concatenation of the two strings (separated by a space) slicing out and swapping the first 2 characters of each. You can assume that the strings are at least 2 characters long. For example:
mixUp('mix', pod'): 'pox mid' mixUp('dog', 'dinner'): 'dig donner'
//This function uses the slice() method. It extracts a part of a string and returns a new string
function mixUp(string1, string2) {
return string1.slice(0, 2) + string2.slice(2) + " " + string2.slice(0, 2) + string1.slice(2);
}
Create a function called fixStart
. It should take a single argument, a string, and return a version where all occurrences of its first character have been replaced with '*', except for the first character itself. You can assume that the string is at least one character long. For example:
fixStart('babble'): 'ba**le' fixStart('turtle'): 'tur*le'
//This function uses a few new methods and regular expressions
function fixStart(inputString) {
var firstChar = inputString.charAt(0);
return firstChar + inputString.slice(1).replace(new RegExp(firstChar, 'g'), '*');
}
Write a function that compares two numbers and returns the larger one. Be sure to try it our with some different numbers. Bonus: add error messages if the numbers are equal or cannot be compared.
Don't forget to test it!
function greaterNum(num1, num2) {
if (num1 === num2) {
console.log ('Those numbers are equal');
return num1;
} else if (num1 > num2) {
return num1;
} else if (num2 > num1) {
return num2;
} else {
console.log ('Those are simply incomparable!');
return undefined;
}
}
console.log (greaterNum(3, 3));
console.log (greaterNum(7, -2));
console.log (greaterNum(5, 9));
console.log (greaterNum(5, 'dog'));
Write a function pluralize
that takes in two arguments, a number and a word, and returns the plural. For example:
pluralize(5, 'cat'): '5 cats' pluralize(7, 'turtle'): '7 cats'
Bonus: Make it handle a few collective nouns like "sheep" and "geese".
function pluralize(number, noun) {
if (number != 1 && noun != 'sheep' && noun != 'geese') {
return number + ' ' + noun + 's';
} else {
return number + ' ' + noun;
}
}
console.log('I have ' + pluralize(0, 'cat'));
console.log('I have ' + pluralize(1, 'cat'));
console.log('I have ' + pluralize(2, 'cat'));
console.log('I have ' + pluralize(3, 'geese'));
Write a for loop that will iterate from 0 to 20. For each iteration, it will check if the current number is even or odd, and report that to the screen (e.g. "2 is even")
for (var i = 0; i <= 20; i++) {
if (i % 2 === 0) {
console.log(i + ' is even');
} else {
console.log(i + ' is odd');
}
}
Create an array to hold your top choices (colors, presidents, whatever). For each choice, log to the screen a string like: "My #1 choice is blue." Bonus: Change it to log "My 1st choice, "My 2nd choice", "My 3rd choice", picking the right suffix for the number based on what it is.
var choices = ['red', 'orange', 'pink', 'yellow'];
for (var i = 0; i < choices.length; i++) {
console.log('My #' + (i + 1) + ' choice is ' + choices[i]);
}
for (var i = 0; i < choices.length; i++) {
var choiceNum = i + 1;
var choiceNumSuffix;
if (choiceNum == 1) {
choiceNumSuffix = 'st';
} else if (choiceNum == 2) {
choiceNumSuffix = 'nd';
} else if (choiceNum == 3) {
choiceNumSuffix = 'rd';
} else {
choiceNumSuffix = 'th';
}
console.log('My ' + choiceNum + choiceNumSuffix + ' choice is ' + choices[i]);
}
Keep track of which books you read and which books you want to read!
var books = [
{title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}];
for (var i = 0; i < books.length; i++) {
var book = books[i];
var bookInfo = book.title + '" by ' + book.author;
if (book.alreadyRead) {
console.log('You already read "' + bookInfo);
} else {
console.log('You still need to read "' + bookInfo);
}
}
var img = document.getElementById('hplogo');
img.width = 400;
img.src = 'http://www.logostage.com/logos/yahoo.GIF';
var button = document.getElementById('gbqfba');
button.innerHTML = 'Yahoooo!';
h1
of "My Book List".p
element with the book title and author and append it to the page.ul
and li
to display the books.img
element for each book on the page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Book List</title>
</head>
<body>
<h1>My Book List</h1>
<script>
var books = [
{title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}];
for (var i = 0; i < books.length; i++) {
var bookP = document.createElement('p');
var bookDescription = document.createTextNode(books[i].title + ' by ' + books[i].author);
bookP.appendChild(bookDescription);
document.body.appendChild(bookP);
}
// Or, with the bonuses:
var books = [
{title: 'The Design of EveryDay Things',
img: 'http://ecx.images-amazon.com/images/I/41j2ODGkJDL._AA115_.jpg',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
img: 'http://ecx.images-amazon.com/images/I/41Z56GwEv9L._AA115_.jpg',
author: 'Brian Christian',
alreadyRead: true
}];
var bookList = document.createElement('ul');
for (var i = 0; i < books.length; i++) {
var bookItem = document.createElement('li');
var bookImg = document.createElement('img');
bookImg.src = books[i].img;
bookItem.appendChild(bookImg);
var bookDescription = document.createTextNode(books[i].title + ' by ' + books[i].author);
bookItem.appendChild(bookDescription);
if (books[i].alreadyRead) {
bookItem.style.color = 'grey';
}
bookList.appendChild(bookItem);
}
document.body.appendChild(bookList);
</script>
</body>
</html>
Write a function that takes a certain type of tag and counts the number of elements with that tag. The function should return "There a X tags of type y on the page.For example:
countTags('p'): 'There are 3 tags of type p on the page'
function countTags (tagType) {
var tagArray = document.getElementsByTagName(tagType);
console.log ('There are ' + tagArray.length + ' tags of type ' + tagType + ' on the page.');
}