Skip to content

Instantly share code, notes, and snippets.

@SnoopSqueak
Last active June 13, 2019 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SnoopSqueak/26824b4bde4071f967100ae3f9628798 to your computer and use it in GitHub Desktop.
Save SnoopSqueak/26824b4bde4071f967100ae3f9628798 to your computer and use it in GitHub Desktop.

Important note

Use Replit or write code in a local JS file to complete these challenges. JS Bin doesn't handle callbacks well (it throws SyntaxError: Unexpected token { even though the code works elsewhere), and Code Pen has a finnicky console: https://repl.it/languages/nodejs

For a hintless version of these questions, use this gist: https://gist.github.com/SnoopSqueak/e5b2eb577b02f7ebb9fcee6d4b22dc6e

Conditionals and operators

  1. Write a function getIsWordOdd that takes in a string and returns true if the word contains an odd number of characters or false if the word contains an even number of characters.

Sample calls:

console.log(getIsWordOdd("Learn")); // should log true
console.log(getIsWordOdd("JavaScript")); // should log false
console.log(getIsWordOdd("Have Fun!")); // should log true

Everyone thinks of addition, multiplication, subtraction, and division as operators, but there are more. We can tell if a number is even or odd by taking its remainder when dividing it by 2. If that remainder is 0, it is even.

It also doesn't matter that the last input is technically two words. They are part of a single string, and based on the directions the function is only concerned about the number of characters, not whether any of them are spaces.

  1. Write a function setLightColor that takes in a string representing the color to set the light to. The function should log "Set light color to " followed by the given color. If the color is "yellow" or "orange", the function should also log "Warning!". If the color is "red", the function should log "Danger!!!". If the color is your favorite color, the function should also log "Hey, that's my favorite color!"

Sample calls where the favorite color is "blue":

setLightColor("green"); // "Set light color to green."
setLightColor("blue"); // "Set light color to blue." "Hey, that's my favorite color!"
setLightColor("yellow"); // "Set light color to yellow." "Warning!"

Sample call where the favorite color is "red":

setLightColor("red"); // "Set light color to red." "Danger!!!" "Hey, that's my favorite color!"

"orange" and "yellow" will both share a condition. "red" will have it's own condition that can only be reached if "orange" or "yellow" was not reached. The favorite color will have its own condition regardless of the warning/danger system.

The user can also enter a string that is not a color. The output might look a bit silly, but if it follows the assignment it's not a problem.

Loops, arrays, and objects

  1. Write a function isBinary that takes in a string and returns true if the string contains only 1s and 0s, or false otherwise.

Sample calls:

console.log(isBinary("101")); // true
console.log(isBinary("one zero one")); // false
console.log(isBinary("10010101001111101")); // true
console.log(isBinary("10 01 10")); // false
console.log(isBinary("")); // true

The most straightforward way to tackle this problem is to loop over each of the string's characters. As soon as it finds a character that is not 0 or 1, it can return false, but if it makes it through the whole string without returning false, it can return true. The placement of the return statements with regards to the loop is important!

  1. Write a function printAnimals that iterates over a given object containing multiple other objects, each representing an animal, and prints out the animal's name and adoption status.

This is the input data:

const animals={beta:{species:"dog",weight:12,sex:"male",name:"Beta",adopted:true},spartacus:{species:"dog",weight:10,sex:"male",name:"Spartacus",adopted:true},rita:{species:"dog",weight:15,sex:"female",name:"Rita",adopted:false},dodger:{species:"dog",weight:13,sex:"male",name:"Dodger",adopted:false},oliver:{species:"cat",weight:9,sex:"male",name:"Oliver",adopted:false},yzma:{species:"cat",weight:10,sex:"female",name:"Yzma",adopted:true},kronk:{species:"cat",weight:11,sex:"male",name:"Kronk",adopted:true}};

Sample call:

printAnimals(animals);

/* expected output:

"Beta is adopted."
"Spartacus is adopted."
"Rita is not adopted."
"Dodger is not adopted."
"Oliver is not adopted."
"Yzma is adopted."
"Kronk is adopted."

end of expected output */

One way to iterate over an object is to use Object.keys(yourObject), which returns an array of all of that object's keys. We can call forEach on that array to get access to each key one at a time. Remember that to get the value for a particular key, we have to go back to the original object.

Object.keys(animals).forEach((animal) => {
  // code can use `animal` to refer to the key;
  //   e.g. beta, spartacus etc.
  // code can use `animals[animal]` to get the actual object
  //   associated with that key.
  // if you're not sure what's going on, try console logging the
  //   key, value, or even JSON.stringify(object) to print out
  //   an entire object. it helps to know what the code is
  //   working with!
});

Callbacks and recursion

  1. Write a function doIfAllowed that takes in two parameters: a string representing a secret phrase, and a function to execute if the secret phrase is the correct phrase. If the given phrase is not the correct phrase, the function should log "You are not allowed to do that." The secret phrase is up to you.

Sample calls, assuming the secret phrase is "let me in":

doIfAllowed("let me in", () => console.log("I'm in!")); // should log "I'm in!"
doIfAllowed("idk", () => console.log("No dice.")); // should log "You are not allowed to do that."
function countToTen() {
  for (var i = 0; i < 10; i++) {
    console.log(i + 1);
  }
}
doIfAllowed("not allowed", countToTen); // should log "You are not allowed to do that."
doIfAllowed("let me in", countToTen); // should log the numbers 1-10.

The doIfAllowed function definition should be pretty simple. function doIfAllowed(phrase, callback) { is a good way to start. Remember that function definitions and function calls are different. When countToTen is passed in as callback, we don't include parentheses on countToTen, since that would evaluate to the returned value (undefined). Instead we pass the function without calling it. That way, if doIfAllowed decides we're allowed to run the code, it can call callback() for us.

  1. Write a function tellStory that takes in an array of strings representing animal names and logs a story about each animal. The first animal can't sleep, so their mother tells them a story about the next animal; that animal can't sleep, so that animal's mother tells them a story about the next animal; etc. The last animal in the array does fall asleep, and after that the other animals can also fall asleep. You don't have to worry about indentation if you don't want to.

Sample call:

tellStory(["child", "frog", "bear", "weasel"]);
/* sample output

"A child couldn't sleep, so her mother told a story about a little frog,"
" who couldn't sleep, so the frog's mother told a story about a little bear,"
"   who couldn't sleep, so the bear's mother told a story about a little weasel,"
"     ...who fell asleep."
"   ...and the little bear fell asleep;"
" ...and the little frog fell asleep;"
"...and the little child fell asleep;"

end of sample output */

One of the most important parts of defining a recursive function is determining the base case. Another very important thing to keep in mind is when to make the recursive call. In this case, each child will log one line, then probably make the recursive call (except the base case of course), then log another line.

Classes and subclasses

  1. Write a class called Rectangle that takes in a width and a height. Give it an area function that returns the product of width and height.

Write a class called Square that extends Rectangle and only takes in length. Since a square is a rectangle with all sides the same length, it can pass in that length for width and height.

Sample calls:

console.log(new Rectangle(10, 5).area()); // should log 50
console.log(new Rectangle(3, 9).area()); // should log 27
console.log(new Square(5).area()); // should log 25
console.log(new Square(10).area()); // should log 100

The Rectangle class only needs two functions, the constructor and area. The Square class only needs a constructor, since it will inherit the rest from Rectangle. The Square class can use super in its constructor to call the parent's constructor. The confusing part is that the Square constructor only expects one number, but the Rectangle expects two, so when Square calls super in the constructor, it has to pass in the length input twice, once for width and once for height.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment