You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
NOTE: Perfectly valid solutions can be written in a different style than the solutions below. If your code works, it works! Don't feel like your functions need to have the exact same syntax as these solutions.
Repeating a String n Times: Let's write a function called
repeatString that takes two parameters: a string str, which is the string
to be repeated, and count -- a number representing how many times the
string s should be repeated, e.g.
Your task is to implement the repeatString function using a while loop.
More Practice
Modify your sum function from the Basic Requirements section to accept
two parameters, start and end: sum should now compute the sum of the
numbers from start to end, e.g.
Let's pretend for a moment that JavaScript does not have the addition
operator + -- instead, it comes with two functions called inc and dec
that perform increment and decrement respectively:
// ignore the fact that inc makes use of +functioninc(x){returnx+1;}functiondec(x){returnx-1;}
Your task is to write a function called add that takes two numbers as
parameters, x and y, and adds them together. The catch is that you can
only use inc and dec to accomplish this.
Write a function called isEven that, given a number n as a parameter,
returns true if that number is even, and false otherwise; however, you
need to do this without using the % operator.
Write a function called multiply that accepts two numbers as parameters,
and multiplies them together -- but without using the * operator; instead,
you'll need to use repeated addition.
That is, fib(0) is 1, fib(1) is 1, fib(2) is 2, fib(3) is 3, fib(4)
is 5, etc.
Notice that each fibonacci number can be computed by adding the previous
two fibonacci numbers, with the exception of the first two: fib(0) and
fib(1). More succinctly,
fib(0) is 1
fib(1) is 1
fib(n) is fib(n - 1) + fib(n - 2)
Write a function called fib that accepts a number n as a parameter and
computes the nth fibonacci number using the above rules.
// Using a for loopfunctionfibF(n){varresult=[1,1];for(leti=2;i<=n;i++){consta=result[i-1];constb=result[i-2];result.push(a+b);}returnresult[n];}// Using recursion (function calls itself)functionfibR(n){if(n<2){return1;}returnfibR(n-1)+fibR(n-2);}
By now you should have worked with the length property of strings, e.g."hello".length. Your task is to write a function called stringLength that
accepts a string as a parameter and computes the length of that string;
however, as you may have guessed, you are not allowed to use the length
property of the string!
Instead, you'll need to make use of the string method called slice. To
get an idea of how slice works, try the following at a console:
"hello".slice(0);"hello".slice(1);"".slice(1);
For our purposes, we can consider slice as taking one argument -- the
index to begin slicing from, and returns a new string starting from that
index onwards.
Indices are positions of characters within strings, and they always
begin counting from 0, e.g.:
// "h e l l o" (spaces added for clarity)// | | | | |// 0 1 2 3 4
The "h" character has index (position) 0 in the string "hello", "e"
has index 1, l has index 2, etc.
Write a function called countChars that accepts two parameters: a string
and a character. This function should return a number representing the
number of times that the character appears in string. To access the
first element of a string, you can use the following syntax:
// access the element at index 0"hello"[0];// => "h""dog"[0];// => "d"
HINT: You'll also need to make use of the slice method as shown above
in the exercise on computing the length of a string.
Implement a function called indexOf that accepts two paramters: a string
and a character, and returns the first index of character in the
string. You'll need to make use of the techniques for accessing the first
element of a string and the rest of the string (slice) as before.
functionindexOf(str,char){varindex=0;while(str.length){if(str[0]===char){returnindex;}index=index+1;str=str.slice(1);}// If the character is not found in the string, return -1 to indicatereturn-1;}
Create arrays in the global scope of your program consisting of strings that represent:
Your favorite TV shows/movies
Names of people you know/care about
Favorite sports/activities
Accessing Array Elements
Using the arrays that you created in the last exercise, use the console to access:
First elements,
Last elements,
Other elements!
Write a function first that takes an array as an argument and returns the
first element in that array.
functionfirst(arr){returnarr[0];}
Write a function last that takes an array as an argument and returns the
last element in the array. Hint: What is the relationship between the
index of the last element in the array and the length of the array?
What is returned by push? Before throwing this into the console, form a
hypothesis about what you think the return value will be:
vararr=[5,7,9];arr.push(6);// => ???
Were you correct? What is the returned by push? Does unshift work in the
same way?
ANSWER:
Both .push() and .unshift() return the length of the new array.
We can use the assignment operator (=) to replace elements in arrays with
other ones like so:
varanimals=['dog','elephant','zebra']// let's replace 'dog' with 'hippo'animals[0]='hippo';animals;// => ['hippo', 'elephant', 'zebra']
Using the same principle, perform the following:
// 1. Change all odd numbers to be those numbers multiplied by two:varnumbers=[4,9,7,2,1,8];numbers[1]=numbers[1]*2;numbers[2]=numbers[2]*2;numbers[4]=numbers[4]*2;numbers;// => [4, 18, 14, 2, 2, 8]// 2. Fix the typos by replacing each element with a correctly spelled versionvarplaces=['snfranisco','oacklannd','santacrus']places[0]='san francisco';places[1]='oakland';places[2]='santa cruz';places;// => ['san francisco', 'oakland', 'santa cruz']
More Practice
Write a function called nth that accepts an array and an index as
parameters, and returns the element at that index.
Write a function rest that returns all the elements in the array except
for the first one. HINT: Read about the slice method on
MDN
and/or experiment with slice at the console like so:
Complete the function conj that accepts an array and an element, and
returns an array with the element added to the end of the array:
functionconj(array,x){array.push(x);returnarray;}
What benefit(s) might there be to using functions like cons or conj over
unshift or push?
ANSWER:
The array that we are modifying is being returned to us when we use these functions, whereas .unshift() and .push() return the array's new length. It is often the case that we want to perform addition operations using the array after it has been modified; using these functions makes doing so easier.
Try the following in a console:
vararr=[];arr[7]="Hello."arr;// => ???
What is the value of arr after assigning an element to its seventh index?
Explain the result in plain English.
ANSWER:
The value of arr is an array with the following characteristics:
Length of 8
Contains 7 empty elements (indices 0-6)
Contains the string "Hello." as its 8th element (index 7)
In order to assign a value at index 7 (arr[7] = "Hello.") JavaScript has inserted empty elements at all preceding indices. It may help to think of arrays like a collection of boxes in which we can store values, with each box representing an element at a given index. In order to have a value in our 8th box (arr[7]), we must have the other boxes that came before it, even if they are empty.
Advanced
Without running the below function, use a whiteboard to figure out what it
should return by repeatedly expanding function invocations:
"the quick brown fox jumped over the lazy dog".split(" ");"Hello, world!".split("")"1,2,3,4,5,6".split(",")
What is returned by split (You can read more about it
here),
and how does it work?
ANSWER:
The split() method splits a string into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split. This separator string is the argument passed to .split(). The return value is the array of substrings.
Use split to write a function longestWord that takes a string as an
argument and returns the longest word.
functionlongestWordFor(str){varsplit=str.split(' ');varlongest=split[0];for(vari=0;i<split.length;i=i+1){if(split[i].length>longest.length){longest=split[i];}}returnlongest;}longestWordFor('all your base are belong to us')// => 'belong';functionlongestWordWhile(str){varsplit=str.split(' ');varlongest=split[0];vari=0;while(i<split.length){if(split[i].length>longest.length){longest=split[i];}i=i+1;}returnlongest;}longestWordWhile('all your base are belong to us')// => 'belong';
Write a function remove that accepts an array and an element, and
returns an array with all ocurrences of element removed.
Write a function shortestWord that works like longestWord, but returns
the shortest word instead.
functionshortestWordFor(str){varsplit=str.split(' ');varshortest=split[0];for(vari=0;i<split.length;i=i+1){if(split[i].length<shortest.length){shortest=split[i];}}returnshortest;}shortestWordFor('all your base are belong to us')// => 'to';functionshortestWordWhile(str){varsplit=str.split(' ');varshortest=split[0];vari=0;while(i<split.length){if(split[i].length<shortest.length){shortest=split[i];}i=i+1;}returnshortest;}shortestWordWhile('all your base are belong to us')// => 'to';
Write a function countChar that takes two arguments: any string, and a
character (string of one letter), and returns the number of times that the
character occurs in the string.
Write a function keep that "keeps" certain elements in an array. The
function will need to take two arguments, an array, and something else --
the second argument will be what is used to determine which elements to keep.
You should be able to use this function to write evens, evenLengthWords,
a hypothetical odds function, or oddLengthWordswithout changing the
keep function.
The values in an object can be objects themselves, and in fact, this is a
very common pattern. For example, consider the following object that
represents a computer:
You should notice that the specs key in the computer object is an object
itself! We could access information about the processor using dot-notation
like so:
Change your object to have a name key, the value of which is an object
– this object should have first, last and middle keys
containing your first, last, and middle names respectively (make sure to
remove the firstName and lastName keys that you added before). You
should be able to access your last name afterwards like so (assuming your
object is called you):
varyou={name: {first: "Michael",middle: "Jeffrey",last: "Jordan"},age: 56,hometown: "Wilmington, NC",occupation: "NBA Owner",dateOfBirth: "February 17, 1963",nbaTitles: 6};you.name.last;// => YOUR LAST NAME
Look up your favorite movie on IMDB, and make an object that represents some
aspects of that movie, e.g.:
Title
Director
Year released
Rating
Actors
HINT: Most movies have multiple actors. What data-structure do we use to
represent a collection of similar things?
Create a new empty object in your console called obj like this:
varobj={};
Add a new key/value pair to the object obj by assigning a new value to a
new key like so:
obj.hello="world";obj["number"]=25;
Now, check the value of obj in the console and ensure that it has the two
key/value pairs added above. This is how we create new key/value pairs in
existing objects.
In the console, add a favoriteColor
key/value pair to the object that represents you.
obj.favoriteColor="Blue";
Accessing Values by Key
Fix the attempts to access values in the person object:
varkey="name";varperson={name: "Alyssa P. Hacker",age: 26,hometown: "somewhere"};person[age];// => 26person.key;// => "Alyssa P. Hacker"
FIXED
person["age"];// => 26person.name;// => "Alyssa P. Hacker"
Write a function fullName that takes a person object as an argument, and
returns that person's full name as a string. By person object, we mean an
object that has the structure of the object you created to represent
yourself above, for example:
Your fullName function should work correctly regardless of whether or not
the person has a middle name -- if it doesn't produce the output shown above
when given the object {name: {first: "John", last: "Doe"}}, fix it so that
it does.
Add the object representing yourself to this array of people (if your
name key does not have the same "shape" as the ones above, make sure you
change it to look like these).
Write a function that, when passed an array of people (person objects) as
an argument, returns an array of their full names. Can you make use of
your fullName function here?
The following object has a number of key/value pairs that need to be removed:
vardirtyObject={_fht: 192492,name: "Alyssa P. Hacker",age: 26,_byz: 939205,_ttrs: 510852}functionclean(obj){// ...}clean(dirtyObject);// => {name: "Alyssa P. Hacker", age: 26}
The function clean should accept an object as an argument and return a new
object that has all of the key/value pairs of its parameter except for those
that begin with _.
Write a function removeOddValues that takes an object as an argument and
returns an object with all key/value pairs removed for which the value holds
an odd number. You'll need to use the `typeof` operator to first check that
the values are numbers:
typeof"Hello"typeof3
More Practice
Look around at various physical objects in the room, or think about
activities that you enjoy. How would you represent this things as objects?
Practice creating objects to represent different things. Some ideas include:
Your favorite drink
A recipe
Sports or hobbies
Your car/bike/hoverboard/vehicle-like thing
Literally anything
Write a function countWords that, when given a string as an argument,
returns an object where keys are the words in the string, and values
are the number of occurrences of that word within the string:
HINT: You will want to make use of the string method split. Try
\"Hello hello".split(" ") at a console to see how it works.
Modify countWords to be case insensitive by using the following string
method (experiment at a console with it to learn its behavior):
"HElLo".toLowerCase();// => ???
Write a function countCharacters that, when given a string as an argument,
returns an object containing counts of the ocurrences of each character in
the string.
HINT: You will want to make use of the string method split. Try
\"hello".split("") at a console to see how it works.
Write a function select that accepts two arguments: an object and an
array. The array should contain names of keys that will be selected from
the object: