Declare a variable total that has the default value of 0 (lowest possible score).
let total = 0;
// Worth thinking about: Why did we use `let` instead of `const` here?
Declare another object that will store the die numbers and counts of each number.
It will be an empty object to start.
const dieCountTracker = {};
Iterate over the input array dice (i.e. visit every die in dice) to track each die number.
dice.forEach((die) => {
// If dieCountTracker object doesn't contain the die number (i.e. we're not tracking that number yet), add it to the object and set its value to 1.
if (dieCountTracker[die] === undefined) {
dieCountTracker[die] = 1;
}
// If dieCountTracker object already contains the die number, we increment the count of that number by 1.
else {
dieCountTracker[die] += 1;
}
})
Test that the dieCountTracker object is built properly by console logging the function call.
// Inside the function, after the .forEach:
console.log(dieCountTracker);
// Outside the function:
console.log(greed([2, 3, 2, 6, 4]));
// We should see:
{ '2': 2, '3': 1, '6': 1, '4': 1 }
- Iterate over the `dieCountTracker` object and get the scores.
- Check [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) for what `Object.keys()` does.
```JS
Object.keys(dieCountTracker).forEach((die) => {
// If we have more than 3 of a number, we need to score the triplet value and any remaining single value.
if (dieCountTracker[die] > 3) {
// Add the triplet scores.
total += possiblePoints[`${die}${die}${die}`];
// After "using up" the triplet, check for the single scores and add them.
if (possiblePoints[die]) {
// Note that we subtract 3 to get the remaining number of appearances.
total += possiblePoints[die] * dieCountTracker[die] - 3;
}
}
// If a number appeared exactly 3 times, we only need to add the triplet score.
else if (dieCountTracker[die] === 3) {
total += possiblePoints[`${die}${die}${die}`];
}
// Check for single scores.
else if (possiblePoints[die]) {
total += possiblePoints[die] * dieCountTracker[die];
}
});
Make sure that we return the output from inside the function.
return output;
Test your function by calling it and console logging its output.
console.log(greed([2, 3, 2, 6, 4]));
Afternoon Code-Along
Declaring variables/constants
Most of the time you'll use const to declare arrays and objects.
Note that when you use const, you can modify the contents of the array/object, but you cannot reassign a different array/object to it.
const myArray = [1, 2, 3];
myArray[2] = 10; // Ok. We're just changing the 3rd element from 3 to 10.
myArray = [4, 5, 6]; // Not ok! We can't reassign a completely different array to myArray. But if you used `let` to declare myArray, reassignment would be ok.
Don't declare a variable without the let or const keyword.
We can grab a value from it and make it a new property in the aboutMe object:
aboutMe.topSkill = allSkills[2];
Note that allSkills[2] evaluates to the string 'JavaScript'.
aboutMe will now be:
{ name: 'Samantha', topSkill: 'JavaScript' }
Using conditional statements
We want a descriptive skill achievement depending on what the top skill is.
// Declare a variable to hold the description.
let skillAchievement;
// Check what the top skill is within the aboutMe object.
if (aboutMe.topSkill === 'Excel' || aboutMe.topSkill === 'VBA') {
skillAchievement = `You're a spreadsheet ninja!`;
} else if (aboutMe.topSkill === 'JavaScript') {
skillAchievement = `You're a programming wizard!`;
} else {
skillAchievement = `You're a data guru!`;
}
Now, given what we have in aboutMe, if you print skillAchievement to the console, you should get You're a programming wizard!.
Initialization: declare a variable with an initial value. Only runs once.
Conditional check: loop only runs if condition evaluates to true
Step up: repeated after every iteration. Changes the variable's value.
Let's iterate over the allSkills array and print each element to the console.
for (let i = 0; i < allSkills.length; i += 1) {
const currentSkill = allSkills[i];
console.log(currentSkill);
}
IMPORTANT NOTE: length is not zero-based, but arrays are.
const allSkills = ['Excel', 'VBA', 'JavaScript', 'SQL', 'Tableau'];
allSkills.length; // 5
allSkills[5]; // undefined, because the last element resides at index = 4.
allSkills[4]; // 'Tableau'
The bracket notation allows us to use a variable's value---instead of a literal string, in the case of the dot notation---as a key for an object.
Let's say we want to use a value of an old object as the key of a new object.
// Old object:
const aboutMe = {
name: 'Samantha',
topSkill: 'JavaScript',
};
// Now we want to make a new object with a key that's the topSkill of the old object.
const newAboutMe = {};
newAboutMe[aboutMe.topSkill] = 'Skill level: 5';
// We'll see that the newAboutMe = { JavaScript: 'Skill level: 5' }
// Note that aboutMe.topSkill = 'JavaScript'.
The method works like a for loop but for arrays only. We can use it to iterate over all the elements of an array.
The .forEach method takes in a callback function as an argument.
The callback function takes in one required argument (and other optional ones).
const testArray = [1, 2, 3, 4];
// Note that we're supplying .forEach with an arrow function.
// And the arrow function has an `element` parameter.
testArray.forEach((element) => {
console.log(element);
});
Run the code above, and you should see the following printed to the console:
Review
RPS WITH VBA
VBA Function
We wrote the
Get_Computer_Move()
function so that we can reuse functionalities within somewhere else.Throw_Rock
,Throw_Paper
, andThrow_Scissors
functions.Subprocedure
DisplayResults
Once we find values for
HumanMove
,ComputerMove
, andOutcome
, this procedure knows how to display the result.vbCrLf
& "Computer threw " & ComputerMove & vbCrLf & Outcome, inside aMsgBox
.vbCrLf
gives you a new empty line.MORNING EXERCISE (TimBits with JS)
Parameters
Anything inside the parentheses after the function is called a parameter.
timBits
, we can pass in a number as an argument, and that number will replace the parameter.()
at the end.Pseudo Code
Get into the habit of pseudo-coding!
//
in the begining of a line to turn that line into a comment/pseudo-code./*
and*/
.Arrays in JavaScript
For loop:
()
:let
to declare a variable that'll be modified by the loop later on.let
(orconst
in other situations) when declaring variables.let
becausecurrentNumber
is to be modified later.i += 1
++
is shorthand for+= 1
.if
andelse if
conditionals:else
executes the is the catch-all, default task after all theelse if
s..push()
:==
vs.===
==
means "loosely equal to".===
means "strictly equal to".Intro to Programming
It's the process of creating a set of instructions that tell a computer how to do things.
You already learned some programming when learning VBA!
Why learn programming?
Some Info about JavaScript
JavaScript can run on the frontend (e.g. browsers) and the backend (e.g. servers).
It's flexible, non-blocking, and great for I/O applications.
How to be an effective programmer?
Approach to Problem Solving
Strategy Cheatsheet
"Greed" Dice Game Exercise
Define a function called
greed
. It takes in an array as the input.Declare an object that stores the property/value pairs that correspond to the scoring system.
Declare a variable
total
that has the default value of 0 (lowest possible score).Declare another object that will store the die numbers and counts of each number.
Iterate over the input array
dice
(i.e. visit every die indice
) to track each die number.Test that the
dieCountTracker
object is built properly by console logging the function call.// Outside the function: console.log(greed([2, 3, 2, 6, 4]));
// We should see: { '2': 2, '3': 1, '6': 1, '4': 1 }
Make sure that we return the
output
from inside the function.Test your function by calling it and console logging its output.
Afternoon Code-Along
Declaring variables/constants
Most of the time you'll use
const
to declare arrays and objects.Note that when you use
const
, you can modify the contents of the array/object, but you cannot reassign a different array/object to it.Don't declare a variable without the
let
orconst
keyword.Note that you can declare a variable without a value using
let
:Adding a property to an object
Let's say we start with an empty object:
We can add a new property to
aboutMe
with the dot notation:Now, if you print the
aboutMe
object, you'll see:Note that a property (aka. a key) needs to be accompanied by a value (in this case, the string 'Samantha').
Accessing an element in an array
Let's say we have this array with 5 string elements:
We can grab a value from it and make it a new property in the
aboutMe
object:Note that
allSkills[2]
evaluates to the string 'JavaScript'.aboutMe
will now be:Using conditional statements
We want a descriptive skill achievement depending on what the top skill is.
Now, given what we have in
aboutMe
, if you printskillAchievement
to the console, you should getYou're a programming wizard!
.For loop
*If you'd like to review the basics of a for loop, read this nice and brief tutorial.
Three steps in setting up a for loop:
true
Let's iterate over the
allSkills
array and print each element to the console.IMPORTANT NOTE:
length
is not zero-based, but arrays are.Using bracket notations
The bracket notation allows us to use a variable's value---instead of a literal string, in the case of the dot notation---as a key for an object.
Let's say we want to use a value of an old object as the key of a new object.
Using Array.forEach method
The method works like a for loop but for arrays only. We can use it to iterate over all the elements of an array.
The
.forEach
method takes in a callback function as an argument.Run the code above, and you should see the following printed to the console: