
// Course Notes:
document.getElementById("lesson").innerHTML = `
Comments are used in JavaScript in order to explain what
the code means making it much more readable
There are two ways to write comments in JavaScript:
1. In-line comments
2. Multi-line comments
`;
// Code Examples:
// two forward slashes: // are in line comments
/* this
is
a
multi-line
comment */
// Exercise
document.getElementById("exercise").innerHTML = `
1. Write a short in line comment about why you
learning JavaScript
2. Write a lengthier multi line comment about
your goals for learning and studying programming!
`;
// Exercise Solution:
// I am learning JavaScript because it's the best!
/* I am studying programming so that I can
make an amazing RPG game one day and change
the world with decentralization and AI */
// Course Notes:
document.getElementById("lesson").innerHTML = `
In computing, data is information that has been translated into a form
that is efficient for processing.
JavaScript has 8 different data types for processing:
undefined, null, boolean, string, symbol, bigent, number,
object
When you declare a variable in javaScript, you specify the data type
and you store the value
In order to create a variable with JavaScript we use the keyword b
a string: stores a series of characters with quotations: single ''
or double quotations: ''
a string: 'would be any characters' whereas a number would be any whole number
Just like in algebra how was use a and b to store values: a = 3, b = 2, a + b = 5
`;
// Code Examples:
// string examp[e:
var hello = "Welcome!";
var goodbye = "Peace oot!";
console.log("Exercicse:", goodbye);
// Exercise
document.getElementById("exercise").innerHTML = `
Declare a variable as a number and set it to the number 5
then console log the variable and check that the output equals 5
`;
// Exercise Solution:
var number = 5;
console.log("Solution:", number);
// Course Notes:
document.getElementById("lesson").innerHTML = `
In JavaScript you can assign one variable to another using
the assignment operator: =
Recall declaring and assigning variables:
var hello = 'Welcome!'
`;
// Code Examples:
/* Lets say we are building a game and we want to assign
some characters to say hello and others not to
*/
// this works for 3 characters
// var teacher = 'Welcome!'
// var student = 'Welcome!'
// var friend = 'Welcome!'
// var uncle
// imagine we have 10,000 characters
var hello = "Welcome!";
var teacher = hello;
var student = hello;
var friend = hello;
var uncle;
console.log("Example", teacher, student, friend, uncle);
// Exercise
document.getElementById("exercise").innerHTML = `
Build Your First Basic Calculator in JavaScript
1. Declare two variables as numbers and initialize them.
One variable named five should be initialized to the number 5
Another variable named four should be initialized to the number 4
2. Declare another variable called calculator and using assignment operation
assign to the calculator variable the variable five plus the variable four
so that the results yield 9.
3. Display your result in the Console
4. Bonus! Create your own calculator and share on discord!
`;
// Exercise Solution:
var five = 5;
var four = 4;
var calculator = five + four;
console.log("Solution:", calculator);
// Course Notes:
document.getElementById("lesson").innerHTML = `
An issue with using var to declare variables is that it can easily be over written
ES6, which was a update standardization to JavaScript addressed this issue by introduction
the let variable. If we replace var with let we will then get an error to avoid making the
mistake
let is a great way to remove the possibility of accidentally redefining variables but
ES6 didn't stop there. It gave JS another awesome gift by introducing the const variable
The const variable has all the same features as let but it also is read only. That means
that you can't accidentally reassign the const variable without throwing an error.
`;
// Code Examples:
// problem with var
var tom = 3;
var tom = 4;
// let tom = 3;
console.log("Example1", tom);
const mike = 3;
//mike = 4;
console.log("Example2", mike);
// Exercise
document.getElementById("exercise").innerHTML = `
1. Create a read only variable x and assign it the string 'this is read only'
`;
const x = "this is read only";
console.log(x);
// Exercise Solution:
// Course Notes:
document.getElementById("lesson").innerHTML = `
Another easy way to increment and decrement numbers
in JavaScript is with the operations ++ and --
`;
// Code Examples:
let i = 1;
i++;
console.log(i);
// Exercise
document.getElementById("exercise").innerHTML = `
1. Create a resassignable ES6 variable y which is not read only
and assign it the value of 4.
2. Subtract 1 from y using the decrement operator and
console log the result
`;
// Exercise Solution:
let y = 4;
y--;
console.log(y);
// Course Notes:
document.getElementById("lesson").innerHTML = `
If we want to find the remainder of the division of two numbers
We can use the remainder operator in JavaScript
The remainder operator is the percentage sign: %
The division of two numbers yields the quotient 4 / 2 = 2;
If you take 4 and you split it into two groups you have one group
group A has 2, ,and another group, group B has 2.
What is the remainder?
We can use mathametics to check whether a number is even or odd
with the remainder of the division of the number by 2.
`;
// Code Examples:
console.log("example 1", 4 % 2);
console.log("example 2", 7 % 4);
// group A = 1 group B = 1 group C = 1 group D = 1
// 7 - 4 = 3 R = 3
console.log("example 3", 7 % 3);
// group A = 2 group B = 2 group C = 2
// 7 - 6 = 1 R = 1
const x = 10;
console.log("example check even or odd", x % 2);
// Exercise
document.getElementById("exercise").innerHTML = `
Declare a read only variable remainder equal to the remainder
of 4 divided by 1 using the remainder operator.
Log the result and make an assessment of the number 4!
`;
// Exercise Solution:
const remainder = 4 % 1;
console.log("Solution:", remainder);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Augmented assignment operators ( +=, -= *=, /= ) mathametically changes the value of
the right operand to a variable and assigns the result to the
variable. The types of the two operands determine the behavior of
the assignment operator.
-----
what the heck am i even talking about?? IN ENGLISH PLEASE -
You can assign a variable it's current memory state and then make a
mathematical change to it to modify the variable. This happens quite often
in coding. Ex1
The short hand form of this would be with augmented operators as follow:
Ex2
`;
// Code Examples:
let x = 5;
x = x + 4;
// x+= 4;
console.log("example 1", x);
let y = 5;
// y += 4 is the same as y = y + 4
y += 4;
console.log("example 2", y);
// Exercise
document.getElementById("exercise").innerHTML = `
Declare a reassignable variable a and set it to 10;
Using the augmented product operator multiply a (is the variabler)
by a number which will yield the result 40.
Log the response and share it on the discord!
`;
// Exercise Solution:
let a = 10;
a *= 4;
// a = a * 4;
console.log("Solution:", a);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Escape literals allow us to use quotations and change the indenting
in our strings so that JavaScript can format the strings properly
\' = single quote
\" = double quote
\\ = backslash
\n = newline
\t = tab
`;
// Code Examples:
console.log("example single quote", "tom said: 'hello!' ");
console.log("example double quote", 'mike replied: "hello!" ');
// Exercise
document.getElementById("exercise").innerHTML = `
Log a console message with the following sentence: 'the cat
jumped over the moon' so that each word starts on a new line
`;
// Exercise Solution:
console.log("Solution", "the \n cat \n jumped \n over \n the \n moon");
// Course Notes:
document.getElementById("lesson").innerHTML = `
Concatenating in JavaScript is when you add one string (or append)
to another string
`;
// Code Examples:
const partOne = "what would you";
const partTwo = " like to do today?";
const phrase = partOne + partTwo;
console.log("example 1", phrase);
console.log("example 2", partOne.concat(" for dinner today"));
// Exercise
document.getElementById("exercise").innerHTML = `
1. Initialize a reassignable variable
named newPhrase to the incomplete following sentence: 'once upon a time'
2. Using the Augmented Plus Operator modify the phrase variable so that
the sentence is completed with your own words by concatenating them to
the phrase variable and log your results.
`;
// Exercise Solution:
let newPhrase = "once upon a time";
console.log("Solution:", (newPhrase += " there was a spaceship in my kitchen"));
// Course Notes:
document.getElementById("lesson").innerHTML = `
As we've discussed multiple times already in this course, functions
in JavaScript are the most efficient ways to reuse code and it's what
makes them imperative in programming!
You can pass values in functions as arguments as well
`;
// Code Examples:
// functions are reusable code that take inputs and return
// outputs
function execute() {
console.log("Example 1: Success!");
}
execute();
const x = 3;
const y = 2;
function execute2(num1, num2) {
return num1 + num2;
}
console.log("example 2:", execute2(12, y));
// Exercise
document.getElementById("exercise").innerHTML = `
1. Write a function called calculator that takes any three numbers as
arguments and returns the product of all three numbers
2. Log the result of the function with the following numbers and 23, 44, 12
and find the solution
`;
// Exercise Solution:
function calculator(a, b, c) {
return a * b * c;
}
console.log("Solution:", calculator(23, 44, 12));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Scope in JavaScript refers to the current context of code,
which determines the accessibility of variables to JavaScript.
The two types of scope are local and global:
Global variables are those declared outside of a block.
Local variables are those declared inside of a block.
var variables automatically move to the global scope which
can create unintended problems in you code
using let and const can be much more precise. this can
be evidently seen with functions
`;
// Code Examples:
let x = 2;
function blockOfCode() {
let x = 3;
return x;
}
console.log(blockOfCode(), x);
// Exercise
document.getElementById("exercise").innerHTML = `
`;
// Exercise Solution:
// Course Notes:
document.getElementById("lesson").innerHTML = `
The if/else statement executes a block of code if a specified
condition is true (boolean). If the condition is false, another block of
code can be executed. The if/else statement is a part of
JavaScript's "Conditional" Statements, which are used to perform
different actions based on different conditions.
Booleans are datatype which contain true or false values
let isItRaining = true;
Equality Operators are different than assigment
Assignment Ex: let x = 2;
Equality Operators include: ==, ===, < > <= >=
Ex: x > y, a <= b
`;
// Code Examples:
const x = 2;
const y = 3;
function conditional() {
if (x < y) {
return true;
} else {
return false;
}
}
console.log(conditional());
// Exercise
document.getElementById("exercise").innerHTML = `
Create a timetravel program that can send us back in time! Woohoo
1. Create two const global variables speed and time and initialze speed
and time to any numbers as long as time is less than speed
2. Create an additional reassignable variable called loadData as a boolean
and initialize it to false.
Now we have our global programming variables set up and it's time to
set the wheels in motion!.
3. Write a function timeTravel that takes two arguments x and y. Add
conditional logic to the function that checks whether x is greater than
or equal to y. If this is true then return the function so that loadData
is modified to true. If it's false then return loadData explicitly again
to equal false.
4. Write a second function called nebular that checks to see if loadData
is true or false. If it's true then nebular should run a console log with
the string input: "Welcome to the stone age!"
5. Execute both functions inputting speed and time as
arguments for timeTravel setting speed to x and time to y.
6. Once you succeed in finishing the program watch our for
dinosaurs in the stone age and yabadabadoooooo
`;
// Exercise Solution:
const speed = 2;
const time = 1;
let loadData = false;
console.log("the state of loadData before:", loadData);
function timeTravel(x, y) {
if (x >= y) {
return (loadData = true);
} else {
return (loadData = false);
}
}
function nebular() {
if (loadData) {
console.log("Welcome to the stone age!!!");
}
}
timeTravel(speed, time);
nebular();
console.log("the state of loadData after:", loadData);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Loops can execute a block of code a number of times.
JavaScript Loops
Loops are helpful, in order to repeat the same code
over and over again, and provide different values each time
Often this is the case when working with arrays:
`;
// Code Examples:
let users = ["Ray", "Susan", "Fake Account", "Batman"];
// for loop example
// 3 expressions in the
// for loop
// 1 initialize index
// 2 second expression dTe hnotes
// how long or where do we
// wish to loop until
// 3 we can decide what happens to i
// for the next iteration
// let i = 0;
// for (let i = 0; i < users.length; i++)
for (let i = users.length - 1; i >= 0; i--) {
console.log(users[i]);
console.log(i + 1);
}
console.log("example 1", users.length);
// Exercise
document.getElementById("exercise").innerHTML = `
Create an algorthim using a for loop
that can add the sum of natural numbers up to 50
(You should use ES6 correctly for variable storage)
So positive whole numbers example: 1, 2, 3, etc
The sum of natural numbers of 3 ex: 1 + 2 + 3 = 6
`;
let sum = 0;
const n = 50;
for (let i = n; i >= 1; i--) {
// sum = sum + i;
sum += i;
}
console.log("solution", sum);
import "./styles.css";
// Course Notes:
document.getElementById("lesson").innerHTML = `
Data Structures - Fundamentals!
Arrays store collections of data. One dimensional arrays only have one level (no nests).
Arrays in javascript can contain multiple types: ie booleans strings and integers.
For ex: let oneDimArray = ['house', true, 3]
The length property returns the number of elements in the array EX 1 below
Arrays can get much more complex.
These are what we call multi-dimensional arrays, or arrays that contain other arrays.
observe that this array also contains objects which we will learn more deeply later on
but the main takeaway for now is to understand that multi-dimensional arrays can store
even complex objects.
`;
// Code Examples:
// EX 1:
let oneDimArray = ["house", true, 3];
// the length property:
console.log(oneDimArray.length);
//Exercise
document.getElementById("exercise").innerHTML = `
Array Exercise:
1. Write an array called simpleArray and assign it 3 unique type variables.
2. In order to pass this exercise the array must contain a boolean, a string and an integer
3. Log out the length of the array.
`;
// Exercise Solution:
let simpleArray = [true, "lion", "tiger", "bear", 1, 2];
console.log("result of simpleArray is: ", simpleArray.length);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Acessing Arrays - Retrieving Data
Arrays are not only meant for storing data, but also for retreiving that data.
Quite logically, observe that when we create an array with 5 elements
then there are five items in the array
For ex: newArray = [1,2,3,4,5]
Every element or item in the array is marked in javascript with an index. It is very
important to note that in Javascript array are zero-indexed. That means the first array item
is actually starting at the 0 position and so on and so forth.
In order to retrieve array values we can use bracket notation to select which value
that we want to reference from an array by adding a bracket at the end of the array
with the index selection. This is called bracket notation.
Let's check out an example of how we could assign a value from an array to a variable
with Ex 1 below.
You can also set values to arrays by selecting the value of the array and redefining
that value (Ex 2)
`;
// Code Examples:
// Ex 1 (array assignment value):
let animalArray = ["cat", "dog", "bird", "human"];
let myFavoriteAnimal = animalArray[0];
console.log("my favorite animal is:", myFavoriteAnimal);
// Ex 2 (set array value)
animalArray[2] = "rhino";
console.log(animalArray);
// Exercise
document.getElementById("exercise").innerHTML = `
1. Given the following array: let cityWeatherData = [true, "cold", "summer", "new york"];
it is most likely incorrect that it's cold in the summer time in new york.
Your mission is to change the true value to false.
2. Log out the new values of cityWeatherData
Good luck!
`;
// Exercise Solution:
let cityWeatherData = [true, "cold", "summer", "new york"];
cityWeatherData[0] = false;
console.log(cityWeatherData);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Append Items to an Array using push() and unshift()
Arrays do not have a fixed size as to the limit of items they can store.
Elements can be added and removed over time and the array data is mutable.
Let's look at two methods which can modify arrays by adding new elements into them
at their beginning point and their end points ie: push and unshift
push adds elemets to the end of an array while unshift adds elements to the beginning of
an array. Both methods can pass one or more arguments depending on how much you'd like to add
to an array - it's up to you! :)
Let's check out some examples below. EX 1
`;
// Code Examples:
// Ex 1: pop and push methods
let kitchenItems = ["fork", "knife", "plates"];
console.log(kitchenItems);
kitchenItems.unshift("cabinets");
// what if someone breaks a plate?
kitchenItems.pop();
// now someone buys a new place
kitchenItems.push("plates");
// Exercise
document.getElementById("exercise").innerHTML = `
1. Write a function called dragonBallZ which takes an array parameter
and returns the array.
2. log the results of the dragonBallZ passing into the argument the string 'Bulma'
into the array.
3. Back in the function dragonBallZ, modify the array with the push and unshift methods.
Add to the beginning of the array the strings San Goku and Piccalo, and add at the end
of the array the string Vegeta.
4. Write kamehameha in the discord to celebrate your victory after successfully completing
the task. ;)
`;
// Exercise Solution:
function dragonBallZ(array) {
array.unshift("San Goku", "Piccalo");
array.push("Vegeta");
return array;
}
console.log("Exercise Solution", dragonBallZ(["Bulma"]));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Modifying Arrays - Remove Items with pop and shift in JavaScript
We've looked at push() and unshift() to add elements to an array.
We can do the exact opposite with their opposite counterparts (almost spooky).
We can use the pop() and shift() methods to remove items in arrays where
pop will remove the last element in an array while shift removes the first element
in an array.
It's important to note that while push and unshift takes arguments to pass into new data,
the pop and shift methods take no arguments and are simply called like such pop(), shift()
Ex 1 of pop and shift below
`;
// Code Examples:
// Example 1: Pop and Shift methods
let outdoorClothes = ["raincoat", "shoes", "hat", "umbrella"];
console.log("Example One:", outdoorClothes);
outdoorClothes.pop();
outdoorClothes.shift();
// Exercise
document.getElementById("exercise").innerHTML = `
1. Write a function called eBooks which takes an argument array.
2. Log eBooks in the console and pass into the array the following books as strings:
Lord Of The Rings, Infinite Jest, Javascript, The Good Parts
3. Within the eBook function, using the pop and shift methods, modify the array so that it
removes ONLY the Infinite Jest book.
4. Share your solution in the discord.
`;
// Exercise Solution:
function eBooks(array) {
let pop = array.pop();
let shift = array.shift();
return [pop, shift];
}
console.log(
"Exercise Solution",
eBooks(["Lord Of The Rings", "Infinite Jest", "Javascript, The Good Parts"])
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Removing Elements from Arrays with Splice
Now that we've covered how to remove elements in the beginning
and the end points of an array, let's look at a more customizable way
to remove elements from anywhere we'd like in the array with the splice() method.
Splice can effectively remove any number of items from an array consecutively from
any given starting point that we input.
Splice can take three arguments. The first argument is for selecting the starting
position of where we remove items (*with the zero index) and the second argument
denotes how many items will be consecutively deleted from the starting position.
Ex 1 Splice Method Below
Splice can also be used to create a new copy of the array with the removed items.
Ex 2 Splice Method To Return A New Array
`;
// Code Examples:
// Example 1: The Splice Method
let colorsArray = ["blue", "green", "brown", "black"];
console.log("Example 1:", colorsArray);
colorsArray.splice(2, 2);
// Example 2: Splice Method To Return A New Array with Removed Items
let array = [1, 2, 3, 4];
let newArray = array.splice(2, 2);
console.log("Example 2:", newArray);
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Use Splice to decode the puzzle
OBJ: You work for the CIA and your job is to decode an unusual communicaiton of strings
with a hidden message using the splice method. The final sentence should only contain
the following indexed values of the INITIAL string arrays: 2,3,5,6,7
1. Initialize an array called jumbled with the following strings consecutively:
'unlock', 'hidden', 'the', 'cat', 'messages', 'jumped', 'over', 'the moon'
2. You can only use the splice method to selectively decode and return the final message
logged in the console.
BONUS Return the deleted items to a new variable called CIAConfidential and share both
confidential decoded logs in the discord.
Good luck saving the world!
`;
// Exercise Solution:
const jumbled = [
"unlock",
"hidden",
"the",
"cat",
"messages",
"jumped",
"over",
"the moon"
];
// Bonus:
function CIA() {
let newJumbled = [...jumbled];
let CIACOnfidential = newJumbled.splice(0, 2) + newJumbled.splice(2, 1);
return CIACOnfidential;
}
console.log("Bonus:", CIA());
jumbled.splice(0, 2);
jumbled.splice(2, 1);
console.log("Exercise Solution:", jumbled);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Adding To Arrays with Splice in Javascript
We've seen how the first two arguments of splice are used for selecting
a starting position and then inputting the number of elements to be removed or
deleted. There is also a third argument to splice as well.
The third argument of splice allow you to swap out the elements you are removing
with new variables.
Ex 1 (Splice - Swapping in New Elements)
`;
// Code Examples:
// Example 1: Splice - Swapping in New Elements
let FixMePlease = ["this", "sentence", "broken", "pie", "now"];
console.log("Example 1:", FixMePlease);
FixMePlease.splice(2, 2, "is", "fixed");
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise Update User Names with Splice
1. Declare the function updateUserNames which takes an array as an argument and return
the array.
2. Log to the console updateUserNames and append the following string literal names
to the array: 'Thomas', 'Suzie','Jessica','Jonny'
3. Back in the updaetUserNames function, update the user names of the array by replacing
'Suzie' with the new user 'Bob' using the splice method.
4. Celebrate your victory once you are successful!
`;
// Exercise Solution:
function updateUserNames(array) {
array.splice(1, 1, "Bob");
return array;
}
console.log(
"Exercise Solution",
updateUserNames(["Thomas", "Suzie", "Jessica", "Jonny"])
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
How To Clone Arrays (make copies) with Slice
Slice is a method which can copy an array's data to new storage without modifying the
original array.
Slice takes two arguments. The first is the position to start copying data and the
second one is where we wish to stop copying the array's data (up to and not including).
Ex 1: Copy an Array with Slice
`;
// Code Examples:
// Example 1: Copy an Array with Slice
let trainingData = ["10,000 steps", "7 Javascript Exercises", "4 React Videos"];
let codingData = trainingData.slice(2, 3);
console.log(
"Example one:",
"coding data:",
codingData,
"training data:",
trainingData
);
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: Update CryptoCurrency Portfolio Data
1. Declare a function called cryptoPortfolio which returns the argument arr of an array.
2. Log out cryptoPortfolio into the console passing the following crypto data as strings:
'Bitcoin', 'Ethereum', 'Solana', 'Ada', 'Chainlink'
3. Within the crpyotPortfolio function, duplicate our user's
crypto portfolio of only the large caps (Bitcoin and Ethereum)
into a new array called newArray and modify the function so that it
returns the new array instead of the original one.
4. Share your solution in our discord in the #datastructures channel.
5. Good luck and may the defi be with you!
`;
// Exercise Solution:
function crpyotPortfolio(array) {
let newArray = array.slice(0, 2);
return newArray;
}
console.log(
"Exercise Solution",
crpyotPortfolio(["Bitcoin", "Ethereum", "Solana", "Ada", "Chainlink"])
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
How To Copy an Array with the Spread Operator in JavaScript
If you just would like to simply copy all of an array's data without making
speciications we can easily employ ES6's helpful method, the spread operataor:
Simple and easy Syntax: ...
Example 1: Copy an entire array with the spread operator
`;
// Code Examples:
// Example 1: Copy an entire array with the spread operator
let weatherReport = ["cold", "13 degrees", "cloudy", "incoming tornado"];
let copyWeatherReport = [...weatherReport];
console.log("Example 1", copyWeatherReport);
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: Make Multiple Array Copies with The Spread Operator
1. Declare a variable called numberofCopies and set the value to 4.
2. Create a function called makeFourCopies which takes an argument array as an array.
3. Log into the console the function makeFourCopies passing into it the following string
data: 'gains', 'losses', 'losses'
4. Back in the makeArrayCopies function, make multiple copies of the array data (
make the EXACT amount of copies as the value in numberOfCopies) into
a new array return the new array and share your solution on the discord.
Good luck!
`;
// Exercise Solution:
let numberOfCopies = 4;
function makeArrayCopies(array) {
let newArr = [];
for (let i = numberOfCopies - 1; i >= 0; i--) {
newArr.push([...array]);
}
return newArr;
}
console.log(
"Exercise Solutoin",
makeArrayCopies(["gains", "losses", "losses"])
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Search for items with indexOf in JavaScript
Array data can get fairly large and complex. It can also mutate and change over time including
order and information of what is being added and removed as we have seen up to this point.
That being said, we can use a very handy method that javaScript offers called indexOf which
quickly searches for us whether an element exists in an array or not and which index location
it is being stored in.
Basically, indexOf takes one parameter which is the element you are searching for and returns
the index position. If the element does not exist in the array then it will return the value
-1.
Example 1: Search through an array with indexOf
`;
// Code Examples:
// Example 1: Search through an array with indexOf
let kingsCourt = ["jester", "queen", "throne", "spooky advisor"];
console.log(
kingsCourt.indexOf("throne"),
kingsCourt.indexOf("magic arrows"),
kingsCourt.indexOf("spooky advisor")
);
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: Search for game items and clone the kingdom!
Rumor has it that back at the kingdom the magic arrows have returned. If this is true
you will have to use your wizard powers to save the kingdom by cloning it multiple times
and create parralel worlds to confuse the kingdom's enemies from dicserning the original from
the copies.
1. Write a function called searchAndClone which takes two arguments: array and elem.
2. Log into the console searchAndClone passing in the following kingdom total updated data:
"throne", "silver sword", "magic arrows"
3. Back in the funciton searchAndClone write in logic using the indexOf method to search
and see whether or not the element magic arrows exists in the searchAndClone arr argument.
If magic arrows does exist then add conditional logic so that the function will push two
copies of the argument array into a new array and return the array. Additionally, if the magic
arrows string does not exist as an element in the argument array then return an error message
to the console stating that the magic arrows are not to be found.
4. Save the kingdom from impending doom and post your solution in the discord #datastructures
channel.
Good luck, brave Warlock!
`;
// Exercise Solution:
function searchAndClone(array, elem) {
// Only change code below this line
let num = 2;
let newArray = [];
if (array.indexOf(elem) > -1) {
while (num > 0) {
newArray.push([...array]);
num--;
}
return newArray;
} else {
return "the magic arrows are not to be found";
}
// Only change code above this line
}
console.log(
searchAndClone(["throne", "silver sword", "magic arrows"], "magic arrows")
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Looping through Arrays - Iteration in JavaScript
In JavaScript, it can be quite useful to loop through each element in an array
and do something with the data. Whether it's to search or mutate the array based
on the information that you find and JavaScript offers multiple built in methods
for you to do this.
Some of these powerful methods include forEach(), map(), and every(), however
the most workable one to use is the infamous for loop.
Ex 1: Push each word in a string into a single array
`;
// Code Examples:
// Ex 1: Push each word in a string into a single array
function convertStringToArray(words) {
let wordArray = [];
let wordsSplit = words.split(" ");
for(let i=0;i<wordsSplit.length;i++) {
wordArray.push(wordsSplit[i])
}
return wordArray
}
console.log(
'Example 1', convertStringToArray("almonds pistaccio blueberries straberries chips coffee")
);
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Chunking with Nested Loops
1. Copy the nested arrays chunked from your description into the Exercise Solution portion
of the IDE.
let chunked = [['a','b','c'], ['d','e','f'], ['g','h','i']];
2. Write a function called alphabet that 'unchunks' the nested arrays and returns all the string
elements in chunked into a single array.
3. Log the result and share in the discord in the #datastructures channel.
`
;
// Exercise Solution:
let chunked = [['a','b','c'], ['d','e','f'], ['g','h','i']];
function alphabet() {
let arr = []
// how many times
for(let i = 0; i < chunked.length; i++) {
// each element
for(let j = 0; j < chunked[i].length; j++) {
arr.push(chunked[i][j]);
}
}
return arr
}
console.log('Exercise Solution', alphabet())
// Course Notes:
document.getElementById("lesson").innerHTML = `
Complex Arrays in JavaScript (Multi-Dimensional)
Congatulations - you've just made it to a fairly substantial checkpoint!
We have covered quite a bit on the fundamentals of arrays in JavaScript and not all
that simple either.
These methods and this comprehension will be quite useful later on so keep it closely
in your toolbelt for now and let's move on to one more final lesson on a higher complexity
level for arrays compared to what we have done so far.
In the previous lesson we worked with nested arrays, but with only one level. Arrays
can nest many more levels than that (infinite actually).
Example 1: Deeply Nested Array Structure
`;
// Code Examples:
// Example 1: Deeply Nested Array Structure
let deeplyNestedArray = [[["level three", ["level four", ["level five"]]]]];
console.log("Example One", deeplyNestedArray[0][0][1][1]);
// although this may seem overly complex, it's really not unusual to see
// this out in the wild
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Build A Dungeons & Dragons Multi-Dimensional Array
1. Declare an array called dungeonLevelSeven
2. The array should have seven nested levels.
3. On the third level the array should contain the strings Treasure and Goblins
4. On the fifth level the array should contain the strings strings Ghosts and Nooby Trap
5. On the sixth level the array should contain the string Easter Egg
6. On the deepest level the arriay should contain the string Big Boss
7. Bonus - First access the treasure and skip the goblins and then access the Easter Egg! :)
8. Good luck, brave Wizard!
`;
// Exercise Solution:
let dungeonLevelSeven = [
[
[
"Treasure",
"Goblins",
[["Ghosts", "Nooby Trap", ["Easter Egg", ["Big Boss"]]]]
]
]
];
console.log("Exercise Solution", dungeonLevelSeven[0][0][2][0][2][0]);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Complex Arrays in JavaScript (Multi-Dimensional)
Congatulations - you've just made it to a fairly substantial checkpoint!
We have covered quite a bit on the fundamentals of arrays in JavaScript and not all
that simple either.
These methods and this comprehension will be quite useful later on so keep it closely
in your toolbelt for now and let's move on to one more final lesson on a higher complexity
level for arrays compared to what we have done so far.
In the previous lesson we worked with nested arrays, but with only one level. Arrays
can nest many more levels than that (infinite actually).
Example 1: Deeply Nested Array Structure
`;
// Code Examples:
// Example 1: Deeply Nested Array Structure
let deeplyNestedArray = [[["level three", ["level four", ["level five"]]]]];
console.log("Example One", deeplyNestedArray[0][0][1][1]);
// although this may seem overly complex, it's really not unusual to see
// this out in the wild
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Build A Dungeons & Dragons Multi-Dimensional Array
1. Declare an array called dungeonLevelSeven
2. The array should have seven nested levels.
3. On the third level the array should contain the strings Treasure and Goblins
4. On the fifth level the array should contain the strings strings Ghosts and Nooby Trap
5. On the sixth level the array should contain the string Easter Egg
6. On the deepest level the arriay should contain the string Big Boss
7. Bonus - First access the treasure and skip the goblins and then access the Easter Egg! :)
8. Good luck, brave Wizard!
`;
// Exercise Solution:
let dungeonLevelSeven = [
[
[
"Treasure",
"Goblins",
[["Ghosts", "Nooby Trap", ["Easter Egg", ["Big Boss"]]]]
]
]
];
console.log("Exercise Solution", dungeonLevelSeven[0][0][2][0][2][0]);
// Course Notes:
document.getElementById("lesson").innerHTML = `
What Are Objects in JavaScript - Key/Pair Values
In JavaScript, an object is a standalone entity, with properties and type.
Compare it with a car, for example. A car is an object, with properties.
A car has a color, a design, engine, a material it is made of, etc.
The same way, JavaScript objects can have properties, which define their characteristics.
JavaScript objects are essentially objects which contain keys (properties) that have values.
Example 1: A Basic Javascript Object`;
// Code Examples:
// Example 1: A Basic Javascript Object
const instagramUser = {
name: "john smith",
photos: ["cat", "family", "race car"],
businessAccount: true
};
console.log("Example 1:", instagramUser);
// We can add properties with dot and bracket notation
instagramUser.location = "france";
instagramUser["followers"] = 349;
// bracket notation is required if your property has a space in it
const allFollowers = "all followers";
// Exercise
document.getElementById("exercise").innerHTML = `
Build an uber app customer javascript object database.
1. Write an object called uberCustomer
2. The object needs to take a minimum of 5 properties with values.
3. The properties and values can be whatever you think would be most appropriate
as long as the values are not blank.
4. At least two of the properties and values should be added with either bracket
or dot notation.
5. Share your solution with the discord community!
`;
// Exercise Solution:
const uberCustomer = {
name: "thomas jones",
location: "new york",
rides: 23
};
uberCustomer.creditCard = "mastercard";
uberCustomer["rating"] = 4.3;
console.log("Exercise Solution:", uberCustomer);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Modifying Objects And Accessing Objects in JavaScript
Just like how we've seen arrays can be nested within other arrays, so can objects
nest within other objects. We can access them
similarly with dot and bracket notation in order to modify the objects property values.
Example 1: Modifying an Object with a nested object
`;
// Code Examples:
//Example 1: Modifying an Object with a nested object
let deepObject = {
id: 2395802395,
amount: 10,
time: new Date(),
geolocation: {
city: "Cancun",
country: "Mexico"
}
};
deepObject.geolocation.city = "Tulum";
// if this was a function we would access this with bracket notation..
let objectTime = deepObject["time"];
console.log("Example 1:", deepObject, objectTime);
// Exercise
document.getElementById("exercise").innerHTML = `
Accessing Weather API Data Structures
You are building a weather application and need to access and modify a copy of the API weather data.
1. Copy a real world Weather API data structure (taken from OpenWeather) under exercise solution
from the description of this video.
2. Assign the weather data to an object called weatherAPI
3. Declare a function checkWeather which can dynamically return either the temperature,
min temperature and humidity
4. Log your results and celebrate good times!
Good luck and fair weather to you.
`;
// Exercise Solution:
let weatherAPI = {
coord: {
lon: -122.08,
lat: 37.39
},
weather: [
{
id: 800,
main: "Clear",
description: "clear sky",
icon: "01d"
}
],
base: "stations",
main: {
temp: 282.55,
feels_like: 281.86,
temp_min: 280.37,
temp_max: 284.26,
pressure: 1023,
humidity: 100
},
visibility: 16093,
wind: {
speed: 1.5,
deg: 350
},
clouds: {
all: 1
},
dt: 1560350645,
sys: {
type: 1,
id: 5122,
message: 0.0139,
country: "US",
sunrise: 1560343627,
sunset: 1560396563
},
timezone: -25200,
id: 420006353,
name: "Mountain View",
cod: 200
};
function checkWeather(scanTemp) {
let data = weatherAPI.main[scanTemp];
return data;
}
console.log("Exercise Solution", checkWeather("temp"));
// Course Notes
document.getElementById("lesson").innerHTML = `
Checking Object Properties in JavaScript
We can use the hasOwnProperty method in javaScript to check whether
a property exists in a object. hasOwnProperty will return a value of
true if it exists and false if it does not.
Example 1: Check whether a property exists
`;
// Code Examples:
// Example 1: Check whether a property exists
const restaurant = {
salad: "romaine",
burgers: true
};
// delete restaurant.burgers
console.log("Example 1:", "burgers" in restaurant);
console.log("Example 1:", restaurant.hasOwnProperty("burgers"));
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: Fix a Bug for A Medical Company's Data
You work at a medical company and you've been getting this weird bug
where the data property 'fever', of whether a patient has a fever
has been oddly and mistakenly replaced with the property 'shoes'.
const medicalData = {
perscriptions: true,
weight: 156,
height: 508,
shoes: false
};
Your boss says he spoke with the doctors and you need to fix this confusing information
ASAP so as not to distract the doctors from their hard work.
1. Write a function cleanUp which will check whether an object contains the property
shoes and delete it if it does. Additionally, create and assign the value of the
property shoes to a new property fever.
2. Log out the solution and share it with the discord! :)
The medical communnity is counting on you! ;) Good luck.
`;
// Exercise Solution:
const medicalData = {
perscriptions: true,
weight: 156,
height: 508,
shoes: false
};
function cleanUp() {
if (medicalData.hasOwnProperty("shoes")) {
medicalData.fever = medicalData.shoes;
delete medicalData.shoes;
}
return medicalData;
}
console.log("Exercise Solution:", cleanUp());
// Course Notes:
document.getElementById("lesson").innerHTML = `
Iterate through Objects with the for...in statement
The for...in statement iterates over all enumerable properties of an object that are
keyed by strings, including inherited enumerable properties.
Example 1: iterate through an Object with for..in
`;
// Code Examples:
// Example 1: iterate through an Object with for..in
let obj = {
character: "knight",
weapon: "long sword",
beard: true
};
for (let attributes in obj) {
console.log("Example 1", attributes);
console.log("Example 1", obj[attributes]);
}
// Exercise
document.getElementById("exercise").innerHTML = `
Given the following object of login information:
let logins = {
week1: true,
week2: false,
week3: true,
week4: true,
week5: true
};
1. Write a function which can calculate and return the total number of logins
using a for...in statement.
And that's all she wrote, folks!
`;
// Exercise Solution:
let logins = {
week1: true,
week2: false,
week3: true,
week4: true,
week5: true
};
function calculateLogins(obj) {
let num = 0;
for (let week in logins) {
if (obj[week] === true) {
num += 1;
}
}
return num;
}
console.log(‘Exercise Solution:’, calculateLogins(logins));
// Course Notes:
document.getElementById("lesson").innerHTML = `
What is Object.keys in JavaScript - storing keys into arrays
You can store all the keys in an object into an array with the Object.keys() method.
Objects.keys takes one argument which is the object you wish to extract the keys from.
Example 1: How to copy keys from an object into an array
`;
// Code Examples:
// Example 1: How to copy keys from an object into an array
let languages = {
french: true,
spanish: false,
english: true
};
console.log("Example 1", Object.keys(languages));
// Exercise
document.getElementById("exercise").innerHTML = `
Write some objects and store their keys into arrays with Objects.keys and don't
forget to have some fun along the way!
`;
// Exercise Solution:
// Course Notes:
document.getElementById("lesson").innerHTML = `
Objects in JavaScript Basics Overview
OK wow... so we've covered pretty much all the key basics for arrays and objects in
JavaScript up to this point! That includes, building, syntax, modifying, cloning, accessing,
iterating and so much more!
Great work going through everything and READY now you are to advance young young padawan into
more complex JavaScript.
Before we dive deep into algorithmic scripting let's take a look at one final exercise for
you to get some practice and test your overall ability and understanding with objects thus far.
If you can succeed in understanding and solving the exercise then consider it your passport
forward. If you struggle, please review any core concepts you may find difficulty with and
come back once you feel newly prepared.
`;
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: Facebook - Delete Friends Functionality
Given the following facebook user object:
let facebookUser = {
handle: "Krystal",
age: 26,
data: {
fullname: "Krystal Ballington",
joinDate: new Date(),
profilePic: "httpsAWS...",
friends: ["Bob", "Jerry", "Ashley"],
groups: [
"New York Squash",
"Spirtual Cooking",
"Fossil Hunting"]
}
};
1. Write a function removeFriend that can search through the
facebook user's info (ie the facebookUser object) and dynamically remove
the friend.
2. The function should take two arguments, the first argument being an object
and the second argument the friend the user wishes to remove.
3. If the friend's name does not exist in the object, the function should return
an error message stating that the friend does not exist.
4. The function should return an array of all of the facebook user's updated friends
list.
This exercise combines an overview of the basics we have been covering in this course
on objects and arrays in javaScript up to this point!
Pass this and prove your valure for more advanced lessons to come.
Brave, you are. Luck, may you have!
`;
// Exercise Solution:
let facebookUser = {
handle: "Krystal",
age: 26,
data: {
fullname: "Krystal Ballington",
joinDate: new Date(),
profilePic: "httpsAWS...",
friends: ["Bob", "Jerry", "Ashley"],
groups: ["New York Squash", "Spirtual Cooking", "Fossil Hunting"]
}
};
function removeFriend(obj, friend) {
let newArray = obj.data.friends;
let i = newArray.indexOf(friend);
if (i > -1) {
// delete userObj.data.friends[i]
newArray.splice(i, 1);// Course Notes:
document.getElementById("lesson").innerHTML = `
Objects in JavaScript Basics Overview
OK wow... so CONGRATULATIONS! we've covered pretty much all the key basics for arrays and objects in
JavaScript up to this point! That includes, building, syntax, modifying, cloning, accessing,
iterating and so much more!
Great work going through everything and READY now you are to advance young young padawan into
more complex JavaScript.
Before we dive deep into algorithmic scripting let's take a look at one final exercise for
you to get some practice and test your overall ability and understanding with objects thus far.
If you can succeed in understanding and solving the exercise then consider it your passport
forward. If you struggle, please review any core concepts you may find difficulty with and
come back once you feel newly prepared.
`;
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: Facebook - unFriend Functionality
Given the following facebook user object:
let facebookUser = {
handle: "Krystal",
age: 26,
data: {
fullname: "Krystal Ballington",
joinDate: new Date(),
profilePic: "httpsAWS...",
friends: ["Bob", "Jerry", "Ashley"],
groups: [
"New York Squash",
"Spirtual Cooking",
"Fossil Hunting"]
}
};
0. Copy the facebookUser object into your exercise solution
1. Write a function unfriend that can search through the
facebook user's info (ie the facebookUser object) and dynamically remove
a friend of choice.
2. The function should take two arguments, the first argument being an object
and the second argument the friend the user wishes to remove.
3. If the friend's name does not exist in the object, the function should return
an error message stating that the friend does not exist.
4. The function should return an array of all of the facebook user's updated friends
list.
This exercise combines an overview of the basics we have been covering in this course
on objects and arrays in javaScript up to this point!
Pass this and prove your valure for more advanced lessons to come.
Brave, you are. Luck, may you have!
`;
// Exercise Solution:
let facebookUser = {
handle: "Krystal",
age: 26,
data: {
fullname: "Krystal Ballington",
joinDate: new Date(),
profilePic: "httpsAWS...",
friends: ["Bob", "Jerry", "Ashley"],
groups: ["New York Squash", "Spirtual Cooking", "Fossil Hunting"]
}
};
function unfriend(obj, friend) {
let array = obj.data.friends;
let i = array.indexOf(friend);
if (i > -1) {
// delete obj.data.friends[i];
array.splice(i, 1);
} else {
return "You have no friends by that name.";
}
return array;
}
console.log("Final Exercise Solution", unfriend(facebookUser, "Sam"));
return "You are not friends with this person";
}
return newArray;
}
console.log(removeFriend(facebookUser, "Bob"));
// Course Notes:
document.getElementById("lesson").innerHTML = `
How to reverse a string in JavaScript
Helper Examples:
The split() method splits a string into an array of substrings, and returns the new array.
The reverse() method reverses an array in place.
The first array element becomes the last, and the last array element becomes the first.
The join() method creates and returns a new string by concatenating all of the elements
in an array (or an array-like object), separated by commas or a specified separator string.
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
1. Write a function which takes the argument of a string and returns another string which holds
the reverse order of characters of the original string.
2. Call the function in the console and test your solution with the argument
'The universe is amazing'
3. Share your solution in the discord channel #algorithms
`;
// Exercise Solution:
// Solution 1
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log("Solution 1:", reverseString("hello"));
// Solution 2
function reverseString2(str) {
let newStr = "";
for (let i = str.length - 1; i >= 0; i--) {
newStr += str[i];
}
return newStr;
}
console.log("Solution 2", reverseString2("hello"));
// Course Notes:
document.getElementById("lesson").innerHTML = `
What is A Factorial - JavaScript (Probability Calculations)
What is factorializing a number and why is this valuable?
Consider having a combination of items and you'd like to know all the possibilities
that these items could form together:
['puzzle peice 1','puzzle peice 2', 'puzzle peice 1']
Now maybe with a small amount we can write it out, but imagine massive numbers..
Factorials allow us to help us calculate probabilities.
Factorials in math are represented with the shorthand notation n!
A factorial is the product of all positive integers less than or equal to n.
so for example 4! = 4 * 3 * 2 * 1 = 24
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: What is A Factorial - JavaScript (Probability Calculations)
1. Declare a function called factorialize which takes a number as an argument.
The function should return the factorial product of the number.
Ie: 4! = 24, 5! = 120 etc
2. Call the function in the console and pass in 7 as the argument and log out the result.
3. Share your solution in the discord and well done!
`;
// Exercise Solution:
function factorialize(num) {
let total = 1;
for (let i = 1; i <= num; i++) {
total *= i;
}
return total;
}
console.log("Solution 1", factorialize(5));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Another classic algorithm scripting challenge!
Program the computer to identify the longest word in a string!
We can do it with our minds and so why not ask our robot friends as well.
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
You are at a coding interview, the interviewer sits you down and asks you to find
the longest word in a string with JavaScript.
1. Declare a function longestWord which takes an input of a string and returns
the longest word in the string.
It's up to you to impress them with your skills and land the golden job!
`;
// Exercise Solution I:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = "";
for (var i = 0; i < str.length; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
console.log(
"Exercise Solution I",
longestWord("we will definitely hire you if you get this right")
);
function longestWord2(string) {
var str = string.split(" ");
var longest = 0;
var word = "";
str.forEach(function (str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
console.log("Exercise Solution II", longestWord2("Get the amazing bonus too!"));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Return The Smallest Numbers in Nested Arrays
Let's challenge our ability to work with nested and multi-dimensional arrays
as well as our understanding of backet notation
Example 1: Math.min()
The Math.min() method returns the number with the lowest value.
Another tip: Math.max() returns the number with the highest value.
`;
// Code Examples:
// Example 1: Math.min()
let array = [0, 42, 4122];
console.log("Example 1:", Math.min(...array));
// Exercise
document.getElementById("exercise").innerHTML = `
Given the following multi-dimensional array:
const multiArray = [[234,35,2,1],[53,3,6554,4],[45,632,31,566]]
1. Write a function smallestNumbers which takes a mult dimensional array as an argument and
returns a new array containing only the smallest integers from each sub array.
2. Log out the function and pass in multiArray as the argument.
3. Share your solutions in the discord channel #algorithms
`;
// Exercise Solution:
const multiArray = [
[234, 35, 2, 1],
[53, 3, 6554, 4],
[45, 632, 31, 566]
];
function smallestNumbers(arr) {
let newArray = [];
for (let i = 0; i < arr.length; i++) {
newArray.push(Math.min(...arr[i]));
}
return newArray;
}
console.log("Exercise Solution", smallestNumbers(multiArray));
// Course Notes:
document.getElementById("lesson").innerHTML = `
How to Repeat A String in JavaScript
There are many ways you could go about repeating a string in javaScript.
The repeat() method is a nice trick introduced in 2015 among others.
Supported Browsers:
Google Chrome 41 and above
Edge 12 and above
Firefox 24 and above
Opera 28 and above
Safari 9 and above
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise: Repeat A String in JavaScript
1. Write a function repeatString which takes two arguments, a string and a number
and return a new string repeating the first string as many times as the number argument
specifies.
2. Log the result in the console and share your solution in the discord.
`;
// Exercise Solution:
// Solution I
function repeatString(str, num) {
let newStr = [];
for (let i = 0; i < num; i++) {
newStr.push(str);
}
return newStr.join("");
}
console.log("Solution I", repeatString("abc", 3));
// Solution II
function repeatString2(str, num) {
return str.repeat(num);
}
console.log("Solution II", repeatString2("abc", 3));
// Solution III
function repeatString3(str, num) {
return Array(num).fill(str).join("");
}
console.log("Solution III", repeatString3("abc", 3));
// Course Notes:
document.getElementById("lesson").innerHTML = `
How to Truncate a string in JavaScript
In mathematics and computer science,
truncation is limiting the number of digits to the right.
Slice is the perfect method to truncate strings
according to your exact specifications.
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Exericse Truncate - Paywall Text Algorithm:
You're working at a Blob The Blog Blog company and they are putting up a
paywall to restrit guest viewers from reading the full article.
Truncate the text so that it only returns up to a maximum value and replaces the
additional overflow with '...'
1. Write a function truncate which takes a string and number as arguments and returns
the string truncated determined by the value of the number argument.
2. Log the result in the console and pass in the arguments:
"Really important stuff you'll pay to read", 16
Guten luck!
`;
// Exercise Solution:
function truncate(str, num) {
if (str.length >= num) {
return str.slice(0, num) + "...";
}
return str;
}
console.log(
"Exercise Solution: ",
truncate("Really important stuff you'll pay to read", 16)
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Hacking A Password with Matching keywords in JavaScript
Finding matching values in javaScript is a very valuable algorithm with many uses.
Consider searching through an array of values and then testing each value to see if
it passes a truthiness test. This is an excellent method to match up values through
testing.
let x = 34,
let y = [12,324325325,3523,235,35, 34...]
expected match = 34
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Exericse - Hacking A Password with Matching keywords in JavaScript
You're walking down the street and suddenly the FBI pulls you over and throws
you in the back of the van! Before you know it, you're at some secret location and are
given instructions to hack into the dark web and help prevent the end of the world!!
0. Insert the following array into your solution script (found in descriptions):
let keywordPossibilities = [
"cat",
"cold",
"this",
"is",
"frame",
"cutey",
"hope"
];
1. Write a function called findMatch which takes two arguments: arr and a function.
2. findMatch should conditionally check whether the function argument given any strings
in the keywordPossibilities are true and if they are to then store the string into the
findMatch function and then finally return the stored string value.
3. If the string does not exist in the array then findMatch should return an error
message stating that there is no match in this file.
4. Log into the console findMatch passing in the keywordPossibilities as the first
argument and an anonymous assertion function for the second argument.
Ex Anonymous function:
function(ar) {
return ar
}
5. The second argument (anonymous function) passed into the findMatch function should take
an argument of a string and return the following assertion:
(copy exactly from the description): return string + " is a match" === "this is a match";
6. Share your solution in the discord #alogrithm channel and best of luck!
`;
// Exercise Solution:
let keywordPossibilities = [
"cat",
"cold",
"this",
"is",
"frame",
"cutey",
"hope"
];
function findMatch(arr, func) {
var word = "";
for (var i = 0; i < arr.length; i++) {
if (func(arr[i]) === true) {
word = arr[i];
return word;
}
}
if (word === "") {
return "there is no match in this file";
}
}
console.log(
"Exercise Solution",
findMatch(keywordPossibilities, function (string) {
return string + " is a match" === "this is a match";
})
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Uppercase - Capitalize letters in strings - JavaScript
When you cycle through strings and wish to mutate the text, it helps to consider
a breakdown of components in values:
IE: string: 'a bunch of words'
C1: a, C2: bunch, C3: of, C4: words
.split(): The split() method divides a String into an ordered list of
substrings, puts these substrings into an array, and returns the array.
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
You're building the front end webiste for a big marketing company in New York.
You're getting the big bucks!
A company exec comes up to you and ask if you can write some algorithms to help
automate the text format on the UI. If you can spruce it up and they increase sales,
a big bonus is coming your way $$$$$
1. Write a function titleCapitalize which can take any string as an argument and return
only the first letter of each word in the string capitalized.
2. Write a second function sentenceCapitalize which can take any string as an argument
and return only the first letter of the first word in the string capitalized.
3. Call and log titleCapitalize with the following argument: 'the future is now'
4. Call and log sentenceCapitalize with the following argument: 'hello, my fiend'
5. Share your solutions on the discord in the #alogrithms channel!
Good luck and bring home that cheddah!
`;
// Exercise Solution:
// Sol I
function titleCapitalize(str) {
str = str.toLowerCase().split(" ");
// console.log(str)
for (var i = 0; i < str.length; i++) {
console.log((str[i] = "gs"));
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
return str.join(" ");
}
console.log("Exericse Solution I", titleCapitalize("the future is now"));
// Sol II
function capitalize(s) {
return s && s[0].toUpperCase() + s.slice(1);
}
console.log("Exericse Solution II", capitalize("hello, my friend"));
// Alt Sol I
function titleCapitalize2(str) {
return str
.toLowerCase()
.split(" ")
.map(function (word) {
return word.charAt(0).toUpperCase() + word.slice(1);
})
.join(" ");
}
titleCapitalize2("Exericse Solution III", "The future is now");
// Course Notes:
document.getElementById("lesson").innerHTML = `
Sort And Order Numbers into an Array in JavaScript
The sort() method sorts the elements in an array in an order
and returns the sorted array.
The default sort order is ascending, built upon converting the elements
into strings, also comparing their UTF-16 code units into values.
Ex: sort((a,b) => (a - b))
The compare function does the following:
if(a < b by some criteria) {
return - 1
}
if(a > b by some criteria) {
return 1
}
a === b then retun 0
Example 1: What Is The Sort Method in JavaScrip
`;
// Code Examples:
// Example 1: What Is The Sort Method in JavaScript
let evenNumbers = [2, 8, 12, 6, 4, 10];
let randomLetters = ["b", "e", "a", "c"];
console.log(
"Example 1",
evenNumbers.sort((a, b) => a - b),
randomLetters.sort()
);
// Example 1: What is the sort method in JavaScript
// Exercise
document.getElementById("exercise").innerHTML = `
Interview Challenge: Sort And Order Numbers into an Array
You are at an interview you get asked the famous sort question but with a TWIST! duh duh duh
The interviewer wants to see if you can go above and beyond and asks you to not only sort a
disordered array of numbers, but also insert any given number into the array in its correct
ordered position.
IE array = [3,35,2,1] and num = 4
script expected output: [1,2,3,4,35]
Prove your valour and show this interviewer what you're made of ;)
Before beginning, create a new array (numbersArray) under the
Exercise Solution section of the template with the following numerical
values in the given order: numbersArray = [120, 420, 12, 3, 24]
1. Write a a function called sortAndOrder which takes two arguments; an array and a number.
2. The function should sort ascendingly and evaluate any given array's numerical values
as well as insert in order any number into the array provided by the number argument of the
sortAndOrder function.
3. Call and log the function sortAndOrder passing in the arguments the
numbersArray and the value 42.
4. Share you solution on the discord in the #alogrithms channel and rejoice victorious!
`;
// Exercise Solution:
// Solution I
let numbersArray = [120, 420, 12, 3, 24];
function sortAndOrder(arr, num) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num) {
arr.splice(i, 0, num);
break;
}
}
return arr;
}
console.log("Exercise Solution I", sortAndOrder(numbersArray, 42));
// Solution II
function sortAndOrder2(arr, num) {
// concat
arr.concat(num).sort((a, b) => a - b);
return arr;
}
console.log("Exercise Solution II", sortAndOrder2(numbersArray, 42));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Anagrams - Decoding Mutations in JavaScript
Anagram: cinema and iceman
rearrange iceman to cinema: iceman - cinema
What if we had an array of two strings that held the exact
same values except in a different order? How could we go about verifying whether
they actually contained the same values or not programmatically?
IE: 1.'hello', 'olleh'
Expected: true
2. 'word', 'friend'
Expected: false
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Write A Program to Solve Anagram Puzzles
Someone stops you on the street and says, 'hey you! Can you please help me!'
Given the following Comparison List:
1. 'dynamite' – 'mayitend'
2. 'Statue of Liberty' – 'Sticky Bird free'
3. 'eleven plus two' – 'twelve plus one'
4. 'dragon king' - 'going Darn'
5. 'the Morse Code' – 'here come dots'
6. 'the nudist colony' – 'no untidy clothes'
1. Create 6 arrays which contain two strings each. The first string in the array
should be the first anagram string and the second string should be the second anagram string we are comparing.
IE: array1 = ['dynamite', 'mayitend']
2. Write a function which can determine whether the following phrase comparisons
are anagrams or not. If they are anagrams the function should return true
otherwise the function should return false!
*Be mindful to not add or change any spaces between phrases as we are not looking
at regex for this example and copy the strings in the description exactly as is.
Please share your solutions in the discord along with only the anagrams that are
actually anagrams.
1. 'dynamite' – 'mayitend'
2. 'Statue of Liberty' – 'Sticky Bird free'
3. 'eleven plus two' – 'twelve plus one'
4. 'dragon king' - 'going Darn'
5. 'the Morse Code' – 'here come dots'
6. 'the nudist colony' – 'no untidy clothes'
`;
// Exercise Solution:
let arr1 = ["dynaMite", "MaYitend"]; // T
let arr2 = ["Statue of Liberty", "Sticky Bird free"]; // F
let arr3 = ["eleven plus two", "twelve plus one"]; // T
let arr4 = ["dragon king", "going Darn"]; // FLAG
let arr5 = ["the Morse Code", "here come dots"]; // T
let arr6 = ["the nudist colony", "no untidy clothes"]; // T
// Solution I
// Course Notes:
document.getElementById("lesson").innerHTML = `
Chunking Arrays into Groups & Subarrays
RECALL!
The array.slice method can extract a slice from the beginning,
middle, or end of an array for whatever
purposes you require, without changing the original array.
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Capture The Flag Groups of Teams
You are a working on a capture the flag style Call of Duty game
regardless whether you're into shooter types or not! :P
Your boss comes up to you asks you to create a function that can
take an array of 6 players and divide them up evenly into 3 teams
each time containing its own sub array of two players.
1. Create an array called captureTheFlagPlayers and input the following
player string data:
["player 1", "player 2",
"player 3", "player 4",
"player 5", "player 6"]
2. Write a function chunkPlayersIntoGroups which can take the
captureTheFlagPlayers array as an argument and return the player data
divided into 3 even teams each containing its own sub array
of two players each.
3. Call and log the function passing in the captureTheFlagPlayers array.
4. Share your solutions on the discord #algorithms channel!
`;
// Exercise Solution:
let captureTheFlagPlayers = [
"player 1",
"player 2",
"player 3",
"player 4",
"player 5",
"player 6"
];
function chunkPlayersIntoGroups(array) {
let temp = [];
let i,
chunk = 2;
for (i = 0; i < 0; i += chunk) {
temp.push(array.slice(i, i + chunk));
}
return temp;
}
console.log(
"Exercise Solution I",
chunkPlayersIntoGroups(captureTheFlagPlayers)
);
function chunkPlayersIntoGroups2(array) {
let temp = [];
let i = 0,
chunk = 2;
while (i < array.length) {
temp.push(array.slice(i, i + chunk));
i += chunk;
}
return temp;
}
console.log(
"Exercise Solution II",
chunkPlayersIntoGroups2(captureTheFlagPlayers)
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Math helpers in JavaScript
Recall:
The Math.max() method returns the largest of the zero or
more number given in an input, or NaN if any paramenter
isn't a number.
`;
// Code Examples:
console.log(Math.min(2, 3, 123));
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Build An Array Calculator
1. Create a calculator function called productAll which can calculate the product of the first
and last number in an array and all of its product numbers in between of the first and last
values.
2. The function should pass an argument as an array and return the product all of values.
IE arr: [1,4] = 24 & arr: [4,43,2,1] = 24
1 * 4 = 4, 2 * 3 = 6, p = 4 * 6 = 26
3. Call and log the productAll function passing in an array with the values [5, 2, 1]
4. Share your math skills with your solution in the discord!
FL: 5 * 1 = 5, MS: 2 * 3 * 4 = 24
5 * 24 = 120
`;
// Exercise Solution:
// Solution I
function productAll(arr) {
let lastValue = arr.pop();
let firstLastSum = arr[0] * lastValue;
let middleSum = 1;
if(arr[0] > lastValue) {
for (let i = lastValue + 1; i < arr[0]; i++) {
middleSum *= i;
}
} else {
if(arr[0] < lastValue) {
for (let i = arr[0] + 1; i < lastValue; i++) {
middleSum *= i;
}
}}
return middleSum * firstLastSum;
}
console.log("Exercise Solution I", productAll([1, 2, 2424, 5, 5]));
// Solution II
function productAll2(arr) {
let lastValue = arr.pop();
let productSum = 1;
let max = Math.max(arr[0], lastValue)
let min = Math.min(arr[0], lastValue)
for(let i = min; i <= max; i++) {
productSum *= i;
}
return productSum
}
console.log("Exercise Solution II", productAll2([1, 2, 2424, 5, 5]));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Virus Detection Algorithm - Asymmetric Arrays
Callback Functions:
A callback function is a function passed into another function as an
argument, which is then invoked inside the outer function to complete
some kind of action.
Example 1: Calling a Function within a function
`;
// Code Examples:
// Example 1: Calling a Function within a function
function Example() {
let greeting = ''
function callB() {
greeting = 'hello'
}
callB()
return greeting;
}
console.log(Example())
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Virus Detection Algorithm - Asymmetric Arrays
You are working client side for a successful start up company. You even have a fooseball table
in the lounge, but it doesn't even matter because you can work remotely on the beach.
Lucky you!
Some hackers get into the client side and implant viruses into the userbase with false accounts.
You boss asks you to locate and track down wihch accounts are causing the malevolent attacks.
Using the cloud database you begin a search to isolate the accounts which do not belong and
track down the bad actors before it's too late.
1. Assign the usersCloud array and usersClient arrays with the following data.
usersCloud = ['tom','susan','jordan','lucy','abraham','jose','maria'];
let usersClient = ['tom','susan', 'VIRUS', 'jordan',
'lucy', 'VIRUS', 'abraham', 'TROJAN','jose','maria'];
2. Create a function virusDetection that can search through two arrays and return a new
array of all the non equal elements in either array
(ie. any element in one array which does not exist in the other array and vice versa.)
3. Call and log the function virusDetection
passing in the two arrays usersCloud and usersClient
4. Share your solution in the discord in the #algorithm channel.
Good luck and show these hackers what's up!
`;
// Exercise Solution:
let usersCloud = ['tom','susan','jordan','lucy','abraham','jose','maria'];
let usersClient = ['tom','susan', 'VIRUS', 'jordan',
'lucy', 'VIRUS', 'abraham', 'TROJAN','jose','maria'];
function virusDetection(arr1, arr2) {
const newArr = [];
function onlyInFirst(firstArray, secondArray) {
for(let i = 0; i < secondArray.length; i++) {
if(firstArray.indexOf(secondArray[i]) === -1)
{
newArr.push(secondArray[i])
}
}
}
onlyInFirst(arr1, arr2);
onlyInFirst(arr2, arr1);
return newArr;
}
console.log(virusDetection(usersClient,usersCloud));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Group Objects by Values in JavaScript
A very useful tool when it comes to grouping ordered information by specific values
is the filter method in JavaScript.
The filter() method creates a new array with all elements
that pass the test implemented by the provided function.
// Arrow function
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )
// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)
Example 1: Filter method example
`;
// Code Examples:
// Example 1: Filter method example
let words = ["truth", "good", "bad", "exuberant"];
console.log(
"Example 1",
words.filter((word) => word.length > 6)
);
function wordFunc(word) {
if (word.length > 6) {
return true;
}
return false;
}
console.log("Example 1 CB", words.filter(wordFunc));
// Exercise
document.getElementById("exercise").innerHTML = `
You are moved into the basement of a company and asked to do some data entry work.
Yikes.
Since you have coding skills, you decide to write some algorithms instead to do the
work for you so you can get out of the basement and get an office with a window and
a view.
1. Given the following array containing objects of employer information:
employees = [
{name: "Tony Stark", department: "Accounting"},
{name: "Peter Parker", department: "Sushi Chef"},
{name: "Bruce Wayne", department: "Accounting"},
{name: "Clark Kent", department: "Mail Room"}
];
1. Write a function called groupingObjectsByValues which takes two arrays as arguments
data and department.
2. The function must check through all the employee information in the data argument
and return into a new global array all the object data of only the accountant employees
including their name and department information.
3. Call and log the groupingObjectsByValues passing in the employees array as the first
argument
Good luck getting out of that basement!
`;
// Exercise Solution:
const employees = [
{ name: "Tony Stark", department: "Accounting" },
{ name: "Peter Parker", department: "Sushi Chef" },
{ name: "Bruce Wayne", department: "Accounting" },
{ name: "Clark Kent", department: "Mail Room" }
];
const accountantsArray = [];
function groupingObjectsByValues(data, department) {
var srcValues = Object.values(department);
// filter the collection
function runDepartmentTest(obj) {
for (var i = 0; i < srcValues.length; i++) {
// console.log(obj.hasOwnProperty(srcKeys[i]))
// console.log(obj)
if (Object.values(obj).indexOf(srcValues[i]) > -1) {
return accountantsArray.push(obj);
}
}
return false;
}
return data.filter(runDepartmentTest);
}
console.log(
"Exercise Solution",
groupingObjectsByValues(employees, { department: "Accounting" })
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Regex matches in JavaScript
Regular expressions are patterns used to match character combinations in strings.
In JavaScript, regular expressions are also objects.
A grouping is like a mini-regex inside of a pair of parenthesis,
while a character set is a range between square brackets.
Example:
/([a-z])([A-Z])/g
So this captures
one character a-z,
one character A-Z
Example 1: Regex for pattern matching and replacing
`;
// Code Examples:
// Example 1: Regex for pattern matching and replacing
let str = "ThreeTwo = Five";
let updatedStr = str.replace(/([a-z])([A-Z])/g, function (match, s1, s2) {
return s1 + " + " + s2;
});
console.log("Example 1: ", updatedStr);
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Star Power with Regex in JavaScript
You are working for a website called Star Power and they just can't get enough
stars. They loves stars so much in fact, so much that they want you to design an
algorithm which will replace all grouping of upper and lowercases with spaces
following by an asterix in between.
Strange request? - Perhaps! But sometimes we just gotta do what the job requires.
For Example -
Given the following string: 'starPower Forever', we should replace it with:
star * power * forever
1. Write a function starPowerAlgo which takes a string as an argument and returns a
new string in all lowercase.
2. The function should replace all groupings of uppercases and lowercases with a space
and should also replace all spaces with an asterix.
IE: The string 'starPower Forever' should be replaced with 'star * power * forever'
2. Call and log the funciton passing in 'starPower Forever'
`;
// Exercise Solution:
function starPowerAlgo(str) {
let arr = [];
let dash = [];
arr = str
.replace(/([a-z])([A-Z])/g, "$1 $2")
.toLowerCase()
.split(" ");
return arr.join(" * ");
/*
for(let i = 0; i < arr.length; i++) {
dash += arr[i] + ' * '
}
let split = dash.toString().split('')
.splice(0, dash.length - 2)
let string = split.join('')
return string
*/
}
console.log("Exercise Solution", starPowerAlgo("starPower Forever"));
// Course Notes:
document.getElementById("lesson").innerHTML = `
Pairing Elements in Multi Dimensional Arrays with JavaScript
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Battle Royale Game - Pairing Elements in Multi Dimensional Arrays
Exercise: You are working on the game 'Battle Royale Mode'. When
the players initially spawn into the arena, depending on their class, they
are given special starting items.
The Knight class is given 'Sword of Power' whereas the Wizard Class is
given the 'Staff of Infernal Blasts' and finally the Thief Class is g
iven the 'Invisibility Dagger'.
IE:
"Knight Class" pairs with 'Sword of Power'
"Wizard Class" pairs with 'Staff of Infernal Blasts'
'Thief Class' pairs with 'Invisibility Dagger'
For the purposes of simplifying the code structure, Knight Class is
denoted by 'K', Wizard Class by 'C' and Thief Class by 'T'
1. Write a function spawnItems which takes a string as an argument
and will match the missing items to the provided player attributes.
2. Return a multi dimensinoal array where the character classes and
its item pairs are paired up in an array,
and all the arrays are grouped into one encapsulating array.
IE: 'K' should yield = [['Kight Class', 'Sword of Power']]
3. Share your solution in the #algorithm channel in the discord!
Good luck and may the schwartz be with you!
`;
// Exercise Solution:
function spawnItems(str) {
let connectedElems = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === "K") {
connectedElems.push(['Knight Class', "Sword of Power"]);
} else if (str[i] === "W") {
connectedElems.push(['Wizard Class', "Staff of Infernal Blasts"]);
} else if (str[i] === "T") {
connectedElems.push(['Thief Class', "Dagger of Invisibility"]);
}
}
return connectedElems;
}
// Course Notes:
document.getElementById("lesson").innerHTML = `
Reduce is a method that can be difficult to understand especially with all the
vague explanations that can be found on the web. There are many benefits to
understanding reduce as it is often used in state management (think Redux).
Reduce is actually just a loop - but a loop with a memory built into it
(in arithmetic we go from left to right )
Example 1: Reduce
Reduce sig:
arr.reduce(callback, initialValue);
`;
// Code Examples:
// Example 1: Reduce
const numbs = [1, 2, 3];
console.log(
"Example 1:",
numbs.reduce((accum, item) => {
return accum + item;
}, -1)
);
const orders = [
{ id: 1, total: 12 },
{ id: 2, total: 22 },
{ id: 3, total: 32 }
];
let total = 0;
for (let i = 0; i < orders.length; i++) {
total += orders[i].total;
}
console.log(total);
console.log(
orders.reduce((accum, item) => {
return accum + item.total;
})
);
// Exercise
document.getElementById("exercise").innerHTML = `
Exercise - Sort Out Facebook Group Users by Location
You are working at Facebook and you need to write an algorithm in order to
filter through two different meetup facebookGroups
so that the users can be organized by their respective countries to help organize
future meetups.
Given the following two arrays of object data:
facebookGroup1 = [
{ name: "cassandra", location: "sweden" },
{ name: "tommy", location: "usa" },
{ name: "eloise", location: "jamaica" },
{ name: "gunita", location: "india" }
];
facebookGroup2 = [
{ name: "voytek", location: "poland" },
{ name: "senja", location: "sweden" },
{ name: "george", location: "sweden" },
{ name: "batman", location: "jamaica" }
];
1. Write a function meetupByLocation which takes a location as an argument
and returns a new flattened array of all the users object data
filtered out by their location. IE. If the argument is 'sweden' then the expected
output should be:
[
{ name: "cassandra", location: "sweden" },
{ name: "senja", location: "sweden" },
{ name: "george", location: "sweden" }
]
2. Log and console your function and pass in 'jamaica' for the location argument.
Share your solutions in the discord and best of luck!!
`;
// Exercise Solution:
const facebookGroup1 = [
{ name: "cassandra", location: "sweden" },
{ name: "tommy", location: "usa" },
{ name: "eloise", location: "jamaica" },
{ name: "gunita", location: "india" }
];
const facebookGroup2 = [
{ name: "voytek", location: "poland" },
{ name: "senja", location: "sweden" },
{ name: "george", location: "sweden" },
{ name: "batman", location: "jamaica" }
];
function meetupByLocation(_location) {
let flattenedArr;
let args = Array.prototype.slice.call(arguments, 1);
flattenedArr = args.reduce(function (accum, item) {
return accum.concat(item);
});
return flattenedArr.filter((i) => {
return i.location === _location;
});
}
// test here
console.log(
"Exercise Solution I",
meetupByLocation("sweden", facebookGroup1, facebookGroup2)
);
function meetupByLocation2(_location) {
let groupArgs = Array.prototype.slice.call(arguments, 1);
let finalGroup = [];
for (let i = 0; i < groupArgs.length; i++) {
let arrArgs = groupArgs[i];
// console.log(groupArgs[i]);
for (let j = 0; j < arrArgs.length; j++) {
let innerVal = arrArgs[j];
if (innerVal.location === _location) {
finalGroup.push(innerVal);
}
}
}
return finalGroup;
}
// test here
console.log(
"Exercise Solution II",
meetupByLocation2("sweden", facebookGroup1, facebookGroup2)
);
// Course Notes:
document.getElementById("lesson").innerHTML = `
Exercise: The Fibonnaci Series in JavaScript
The Fibonnaci is a magical series of numbers in which each number
( Fibonacci number ) is the sum of the two preceding numbers.
The simplest is the series 1, 1, 2, 3, 5, 8, etc.
The golden ratio describes predictable patterns
on everything from atoms to huge stars in the sky.
The ratio is derived from the Fibonacci sequence,
named after its Italian founder, Leonardo Fibonacci.
Nature uses this ratio to maintain balance, and the financial
markets seem to as well.
F(n) = F(n-1) + F(n-2)
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
// Fn(0) = 0, Fn(1) = 1, Fn(2) = 1 Fn(3) = 2, Fn(4) = 3
Example 1: Recursive Fib
Big O notation, indicating the order of growth of some quantity as a
function of n or the limiting behavior of a function, e.g.
in computational complexity theory
`;
// Code Examples:
// Example 1: Recursive Fib
function fibonacciRecursive(num) {
if (num === 0) return 0;
if (num <= 1) return num;
return fibonacciRecursive(num - 1) + fibonacciRecursive(num - 2);
//2 + 1 = 3, 4
// time complexity is exponential
}
console.log("Example I", fibonacciRecursive(6));
document.getElementById("exercise").innerHTML = `
Exercise
Convert Big O Exponential Fibonnaci to a Linear Solution
You are working at a financial company measuring predictive graphs of
indexes and stocks.
1. Your boss asks you to write a function that can calculate the
fibonacci sum of terms in a series that does not have an exponential
time complexity.
IE:
Fib Series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
// Fn(0) = 0, Fn(1) = 1, Fn(2) = 1 Fn(3) = 2, Fn(4) = 3
2. Name the funciton fibonnaciSum. It should take an argument which is the
sequential number position of F(n) in the series and return all the added sums
of each position starting at the value where 1 equals: f(n1) = 1.
For Example:
fibonnaciSum(10)
1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55
expected output: 143
fibonnaciSum(7) - Expected Output: 33
3. Log and call your function passing in 14 as the value and
share your solutions in the #algorithms channel on the discord!
`;
// Exercise Solution:
// 0, 1, 2, 3, 5
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
// Fn(0) = 0, Fn(1) = 1, Fn(2) = 1 Fn(3) = 2, Fn(4) = 3
function fibonacciSum(num) {
let a = 1,
result = 0,
temp;
let sum = 0;
if (num === 0) return 0;
while (num > 0) {
temp = a;
a += result;
result = temp;
sum += result;
num--;
}
return sum;
}
// 1 + 2 + 3 + 5
console.log("Exercise Solution I", fibonacciSum(7));
// 0, 1, 1, 2, 3, 5, 8 , 13
function printFib(num) {
let arr = [];
let calc = 0;
let a = 1,
result = 0,
temp;
let sum = -1;
if (num === 0) return 0;
while (num >= 0) {
temp = a;
a += result;
result = temp;
arr.push(result);
sum += result;
num--;
// console.log(result);
}
let corrVal = arr[arr.length - 2];
for (let i = 0; i < arr.length - 1; i++) {
calc += arr[i];
}
console.log("calc", calc);
return corrVal;
}
console.log(printFib(10));
document.getElementById("exercise").innerHTML = `
Exercise: Model Prediction ML JavaScript Tests
You are working for an ML company specializing in all sorts of
complex calculations that's above your pay grade.
The Pipeline department turns to you and asks if you can write
a script to check and see that all their test case scenarios
are passing. You put on your best thinking hat and exclaim,
'No problem! I got this, buddy!'
Given the following ML Test data and their respective results
{ case_test: "Robot Takeover", pass: true },
{ case_test: "AI In The Fridge", pass: false },
{ case_test: "The Computers Are Winning", pass: true },
{ case_test: "Model Prediction 21", pass: true };
1. Input the object data into an array called mlTests.
2. Write a function PassAllTests which takes an array as the first
argument and object properties as the second and third arguments.
3. If all values of the pass property in mlTests are true then
return a message indicating that all tests are passing and the length of the total tests.
4. If any of the pass properties are false then return an error message indicating
that the test container is failing as well as which case test
specifically is failing.
For EX:
Given:
[
{ case_test: "Robot Takeover", pass: true },
{ case_test: "AI In The Fridge", pass: true },
{ case_test: "The Computers Are Winning", pass: true },
{ case_test: "Model Prediction 21", pass: true }
]
Expected result: All 4 Tests Passing :)
5. Call the function and log your result passing in the appropriate arugments in order
to run the tests correctly and return an accurate and helpful result.
6. Share your solution on the discord and good luck!!
`;
// Exercise Solution:
const mlTests = [
{ case_test: "Robot Takeover", pass: true },
{ case_test: "AI In The Fridge", pass: false },
{ case_test: "The Computers Are Winning", pass: true },
{ case_test: "Model Prediction 21", pass: true }
];
function PassAllTests(testContainer, pass, cases) {
let caseFail = "";
for (let item in testContainer) {
if (!testContainer[item][pass]) {
caseFail = testContainer[item].case_test;
return "Tests Failing. Please check: ".concat(caseFail);
}
}
return `All ${testContainer.length} Tests Passing :)`;
}
console.log("ex 1", PassAllTests(mlTests, "pass", "cases"));
function PassAllTests2(testContainer, pass, cases) {
let caseFail = "";
let counter = 0;
for (let item in testContainer) {
if (testContainer[item][pass]) {
counter++;
} else {
caseFail = testContainer[item].case_test;
}
}
if (counter === testContainer.length)
return `All ${testContainer.length} Tests Passing :)`;
return "Tests Failing. Please check: ".concat(caseFail);
}
console.log("ex 2", PassAllTests2(mlTests, "pass", "cases"));
// Course Notes:
document.getElementById("lesson").innerHTML = `
What is a Palindrome in JavaScript
The difference between anagram and palindrome is that anagram is (of words)
a word or phrase that is created by rearranging the letters of another word or
phrase while palindrome is a word, phrase, number or any other sequence of
units which has the property of reading the same forwards as it does backwards,
character for character, sometimes disregarding punctuation, capitalization and
diacritics.
IE eye = true, eyes = false
Example 1: Recall the Anagram Example
`;
// Code Examples:
// RECALL THE ANAGRAM EXAMPLE:
let arr2 = ["Statue of Liberty", "Sticky Bird free"]; // F
function decodeMutations(arr) {
let array1 = [];
let array2 = [];
array1.push(...arr[0]);
array2.push(...arr[1]);
const lowCase1 = array1.map((char) => char.toLowerCase());
const lowCase2 = array2.map((char) => char.toLowerCase());
let str1 = lowCase1.sort().join("");
let str2 = lowCase2.sort().join("");
console.log("c1 - dynamite:", lowCase1, "c2 - mayitend:", str2);
if (str1 === str2) return true;
else return false;
}
console.log("Example 1:", decodeMutations(arr2));
// Exercise
document.getElementById("exercise").innerHTML = `
Interview Question - Check if a string is a Palindrome
1. Write a function called palindrome that takes a string as a parameter
that returns true if a word is a palindrome and false if a word is not a
palindrome.
2. NOTE that any non-alphanumeric characters (including the underscore) should
be disregarded (for example: ./[[]] should be disregarded).
3. Log and call the function twice passing in the following strings:
"// [_t o t_]" expected output: true
" map" expected output: false
4. Share your solution in the discord and good luck!
`;
// Exercise Solution:
function palindrome(str) {
let array1 = str
.replace(/[^0-9a-z]/gi, "")
.toLowerCase()
.split("");
console.log(array1);
let array2 = str
.replace(/[^0-9a-z]/gi, "")
.toLowerCase()
.split("")
.reverse();
console.log(array2);
const str1 = array1.join("");
const str2 = array2.join("");
console.log("str1", str1);
console.log("str2", str2);
if (str1 === str2) {
return true;
} else return false;
}
console.log(palindrome("// [_t o t_]"));
console.log(palindrome(" map"));
// [_t o t_]
// Course Notes:
document.getElementById("lesson").innerHTML = `
Leet Code Example - Trapping Rain Water (Case Study)
LeetCode is a good tool to help you enhance your skills, expand your knowledge and
prepare for technical interviews. Now although some questions and examples are free,
they do have a subscription to pay for their platfrom services as well.
Let's take a look at a leetcode interview questions together!
`;
// Code Examples:
// Exercise
document.getElementById("exercise").innerHTML = `
Leet Code Example - Trapping Rain Water (Case Study)
1. Given n non-negative integers representing an elevation map where the
width of each bar is 1, compute how much water it is able to trap after raining.
2. Use the following array as your functions input:
[0,1,0,2,1,0,1,3,2,1,2,1]
3. Log and call the function which should successfully return the computation of how
much water this blueprint array is able to trap after raining.
Exercise Solution Explanation:
x axis base = .
* = block of elevation
.......*....
...*rrr**r*.
x .*r**r******
final calc = min(a,b) – array[i],
r = 6
Input: arr[] = {2, 0, 2}
Output: 2
Algorithm:
Traverse the array from start to end.
For every element, traverse the array from start to that index and find the
maximum height (a) and traverse the array from the current index to end, and
find the maximum height (b).
The amount of water that will be stored in this column is min(a,b) – array[i],
add this value to the total amount of water stored
Print the total amount of water stored.
`;
// Exercise Solution:
function maxRain(graphArr) {
let result = 0;
const xPlainMax = graphArr.length;
// For every element of the array
// except first and last element
for (let i = 1; i < xPlainMax - 1; i++) {
let left = 0;
//console.log(i)
//console.log('left',left)
// Find maximum element on its left
for (let j = i; j >= 0; j--) {
// console.log('j',j)
left = Math.max(left, graphArr[j]);
//console.log('graphArr',graphArr[j])
// console.log('left',left)
}
// Find maximum element on its right
let right = graphArr[i];
//console.log('graphArr',graphArr[i])
for (let j = i + 1; j < xPlainMax; j++) {
// console.log('j',j)
// console.log('graphArr',graphArr[j])
// console.log('right',right)
right = Math.max(right, graphArr[j]);
}
// Update maximum water value
result += Math.min(left, right) - graphArr[i];
// console.log('left',left)
// console.log('right',right)
// console.log('graphArr',graphArr[i])
}
return result;
}
console.log("Exercise Solution I", maxRain([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]));
function trap2(heights) {
const maxSoFar = (arr) =>
arr.reduce((m, x) => m.concat(Math.max(...m, x)), []);
const leftWall = (arr) => [0, ...maxSoFar(arr).slice(0, -1)];
const l = leftWall(heights);
const r = leftWall(heights.reverse()).reverse();
return heights.reduce(
(m, h, i) => m + Math.max(0, Math.min(l[i], r[i]) - h),
0
);
}
console.log(
"Exercise Solution II",
trap2([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])
);
Are you familiar with Javascript and programming in general, perhaps considering a coding interview soon, but are looking to train, sharpen and master your Javascript skills and your data structures and algorithms with an anthology of some of the most important practice examples and a journey that can smoothly get you there?
If you understand Javascript conceptually, or have recently just gotten started, but find you still need a solid extra boost to really lock it in and gain confidence as a developer and during interviews, than this course is specifically designed for you!
The reality is that we have all been there on the other side of the table and it doesn't matter how many interesting lessons you've learned, if you don't have enough focused practice experience, problems which would otherwise be quite simple to solve seem needlessly challenging.
This course will cover from the ground up some of the most essential coding interview questions in Javascript and programming data structures and algorithms. We will gradually introduce more and more challenging concepts to give you a complete picture with a master tool box of knowledge to impress your next interviewer and colleagues.
Learning programming feeling fluent and able to write out your thoughts and problem solve on the fly may seem overwhelming, especially when staring at a blank page under pressure, but there is one thing that can break through the barriers for you and take you to the next level - practice.
This course offers an efficient model of hours upon hours of practice examples that come with multiple solutions as well as a glossary of definitions. That way you can move through the course freely at your pace and start at very very beginning of programming in Javascript learning about datatypes or jump right in to leet code examples, matrices, Fibbonaci sequences and much more.
Walking into a coding interview and having the confidence from fresh practice examples is what makes the difference between landing your dream job at a 150K+ versus feeling frustrated and uncertain.
I have worked for some of the biggest Unicorn companies in the valley, as well as have built successful applications with large dev team force and overseen popular interview questions from Google, Amazon, Uber and beyond. This course specifically focuses and encourages a disciplined approach to improving your ability to break down and problem solve data structures and algorithms with Javascript and help lift you up.
Why is this the right Javascript course for you?
This is the most practice friendly for complete beginners to advanced Javascript practice and coding interview Course on Udemy. It's an all-in-one topic by topic focused approach that will take you from the very fundamentals of Javascript and programming, all the way to building advanced algorithms.
You will learn Javascript from the very beginning, step-by-step. I will guide you through the console with many code alongs and examples, important theory about how Javascript works behind the scenes and more.
You will also learn how to problem solve like a developer, how to build out formulas from scratch, the proper conventions for your code, how to debug code, and many other real-world skills that you will need in order to confidently write programs from scratch.
And unlike other courses, this one actually contains beginner, intermediate, advanced, and even expert topics.
But... You don't have to go into all these topics. This is a long course that focuses on Javascript. and The Coding Interview and it is designed to bring you a combination of courses all in one! But you can improve your skills by focusing only on specific parts of this course. You can use this course as the lifetime reference guide for certain topics as you continue to build projects, do interviews, land new jobs and learn more that you can always come back to anytime you wish to advance in a particular topic.
By the end of the course, you will have the knowledge and confidence that you need in order to take on coding interview questions.
Why am I the right Solidity teacher for you?
My name is Clarian, I've worked as a head engineer with top tech and entertainment companies around the world for over 15 years, tech developer, CEO, consultant in the space, and I am fully passionate and dedicated to what I teach.
I have recently been spending my time building comprehensive training models with clear explanations to help others evolve and grow by demystifying common misconceptions and problems.
What do we learn exactly in this course?
Careful and practical definitions, followed by clear examples, and exercises for you to try hands on in which we go over multiple solutions every time.
Essential breakdowns of coding interview questions and solutions for data structures and algorithms that show you how to do it on your own.
An enormous amount of practice exercises. Prepare to train to become a Javascript ninja from working on virus assymetric hacking models, extracting uber databases, accessing game levels, to highly common asked interview questions such as fibonnaci sequences, the rain water matrix, truncating, chunking, and much much more...
Optimization and refactoring techniques to not just write code, but write code that works according to its appropriate context.
Industry level experience and advice including key tricks and tips to look out for.
Q&A and a live online free active school with over 10,000 of my students including graduates and mentors working at Google, AWS, and deep in the startup life.
Lessons include: Palindromes, Truncating, Reversing strings, Assymetric Arrays, Nested Loops, Anagrams, Reg Ex, Async Await, Promises, Recursion, Callbacks, Build calculators, Fetch Databases, Manipulate Data, Virus detection, Formatting Automation, and much much more
Check out the course curriculum for an even more detailed overview of the content :)
This is what's also included in the package:
Consistently updated content with video and downloadable code files you can reference whenever you want.
Clear explanations which come with exercises, solutions, and discussions
An online community of active developers and students is available for support and discussion.
Free support in the course Q&A
This course is for you if...
... you want to gain a clear and advanced understanding of Javascript and coding interview challenges
... you have been trying to learn Javascript but: 1) still don't really understand programming completely, or 2) still don't feel confident to code out problems
... you are interested in working as a programmer in the future
... you already know Javascript and development and are looking for a course to clearly go over advanced topics. This course includes expert topics!
... you want to get started with programming: Javascript is an awesome and very interesting first language!
Does any of the above sound good to you? If so, then whenever you're ready, start this new adventure today, and join me and thousands of other developers in one of the most practice oriented Javascript course that you will ever need!
This Javascript course is ideal for anyone searching for more info on the following: coding interview - data structures and algorithms and practicing and mastering javascript