# Week 2
# Ticket validation
Maak een bestand ticket_validation.js
aan in de reeds aangemaakt folder week-2
- Maak een variable
hasTicket
die een boolean is. Je kiest zelf de waarde (waar of niet waar) - Maak een variable
isVIP
die een boolean is. Je kiest zelf de waarde (waar of niet waar)
Zorg nu dat je een bericht naar de console logt op basis van de volgende voorwaarden:
- Als de persoon een ticket heeft en geen VIP is, log dan
Je hebt een ticket!
- Als de persoon een ticket heeft en een VIP is, log dan
Je hebt een ticket en je bent een VIP!
- Als de persoon geen ticket heeft, log dan
Sorry, je hebt geen ticket
Verander hasTicket
en isVIP
van waarde om zeker te zijn dat je alle scenario’s hebt getest.
./artevelde/pgm-code/pgm-1/week-2/ticket_validation.js
const hasTicket = true;
const isVIP = false;
// optie 1
if (hasTicket && isVIP) {
console.log("Je hebt een ticket en je bent een VIP!");
} else if (hasTicket) {
console.log("Je hebt een ticket!");
} else {
console.log("Sorry, je hebt geen ticket");
}
// optie 2
if (hasTicket) {
if (isVIP) {
console.log("Je hebt een ticket en je bent een VIP!");
} else {
console.log("Je hebt een ticket!");
}
} else {
console.log("Sorry, je hebt geen ticket");
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# BMI indicatie
*[BMI]: Body Mass Index
Bereken de BMI op basis van lengte en gewicht. Er is sprake van ondergewicht als je BMI minder dan of gelijk is aan 18.5. Het aanbevolen gewicht vinden we tussen de waarden groter dan 18,5 en kleiner dan 25. Je hebt overgewicht bij waardes tussen 25,0 en 30 (inclusief). Je bent zwaarlijvig bij een BMI van meer dan 30. Log het bericht op basis van de bovenstaande beredenering (bijv. Je hebt het aanbevolen gewicht
) naar de console.
Maak een bestand bmi_indicator.js
aan in de reeds aangemaakt folder week-2
.
Mogelijke oplossing:Resultaat
Jouw bmi is 21. Je hebt het aanbevolen gewicht.
./artevelde/pgm-code/pgm-1/week-2/bmi_indicator.js
/*
* BMI indicator
* ===================================================================
* Course: Programming 1: Front-End Essentials
* Week: 2
* Developed by: Jannes Lambrecht
* Last updated: 26/09/2022
*/
// Length of the person
const length = parseFloat(1.72);
// Weight of the person
const weight = parseFloat(65);
// Calculate the Body Mass Index (BMI)
const bmi = Math.floor(weight / (length * length));
// Log the BMI to the user
let message = `Your bmi is ${bmi}`;
if(bmi <= 18.5){
message += "Je hebt ondergewicht."
}
else if(bmi < 25){
message += "Je hebt het aanbevolen gewicht.";
}
else if(bmi <= 30){
message += "Je het overgewicht.";
}
else{
message += "Je bent zwaarlijvig.";
}
console.log(message);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Schrikkeljaar
Ga na of een een bepaald jaar al dan niet een schrikkeljaar (Eng. leap year) is.
De flow om een schrikkeljaar te berekenen:
- Begin met het jaar waarvan je wilt weten of het een schrikkeljaar is. Definieer een
const
variabele met de naamyear
en bevat als waarde het jaar om na te gaan of het jaar al dan niet een schrikkeljaar is. - Definieer een
let
variabele met de naamisLeapYear
metfalse
als standaardwaarde. - Kijk of het getal door 4 te delen is (met een heel getal als uitkomst, zonder rest). Als dat niet zo is, zoals bij 1977, is het geen schrikkeljaar. Als het wel zo is, zoals 2012, lees dan verder.
- Kijk of het jaar door 100 gedeeld kan worden. Als een jaar door 4 gedeeld kan worden, maar niet door 100, is het een schrikkeljaar. Als een jaar door zowel 4 als door 100 te delen is, zoals 2000, lees dan verder.
- Kijk of het jaar door 400 gedeeld kan worden. Als een jaar door 100 gedeeld kan worden, maar niet door 400, zoals 1900, dan is het geen schrikkeljaar. Als het door beide getallen te delen is, dan is het een schrikkeljaar. Dus 2000 was inderdaad een schrikkeljaar.
Maak een bestand leap_year.js
aan in de reeds aangemaakt folder week-2
.
./artevelde/pgm-code/pgm-1/week-2/leap_year.js
const year = 1977;
let isLeapYear = false;
if ((0 == year % 4 && 0 != year % 100) || 0 == year % 400) {
isLeapYear = true;
}
// Longer version
// if (year % 4 === 0) {
// if (year % 100 === 0) {
// if (year % 400 === 0) {
// isLeapYear = true;
// }
// } else {
// isLeapYear = true;
// }
// }
console.log(`The year ${year} is ${isLeapYear ? "a leap year" : "not a leap year"}!`);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# First element of an array
Maak een bestand array_first_element.js
aan in de reeds aangemaakt folder week-2
. In deze applicatie loggen we het eerste element uit de array naar het output scherm:
- Definieer een array met de volgende elementen
Evelien
,Mathieu
,Thibault
- Log het eerste element uit deze array
./artevelde/pgm-code/pgm-1/week-2/array_first_element.js
const persons = [`Evelien`, `Mathieu`, `Thibault`];
const firstPerson = persons[0];
console.log(`The first person is ${firstPerson}.`);
2
3
# Last element of an array
Maak een bestand array_last_element.js
aan in de reeds aangemaakt folder week-2
. In deze applicatie loggen we het laatste element uit de array naar het output scherm:
- Definieer een array met de volgende elementen
Frodo
,Rocky
,Bill
- Log het laatste element uit deze array op basis van de lengte van de array
./artevelde/pgm-code/pgm-1/week-2/array_last_element.js
const cats = [`Frodo`, `Rocky`, `Bill`];
const lastCat = cats[cats.length - 1];
console.log(`The last cat is ${lastCat}.`);
2
# Filter even numbers
Maak een bestand filter_even_numbers.js
aan in de reeds aangemaakt folder week-2
. In deze applicatie filteren we de even getallen uit een array naar een nieuwe array.
Begin met een variabele numbers:
const numbers = [10, 18, 17, 11, 7, 30, 85, 37, 24, 29, 49];
- Maak nu een nieuwe array
evenNumbers
aan. Dit is een lege array. - Overloop de array en controlleer elk getal. Is het even dan voeg je het toe aan
evenNumbers
. - Log op het einde de array
evenNumbers
naar de console.
Output
Even numbers: [ 10, 18, 30, 24 ]
./artevelde/pgm-code/pgm-1/week-2/filter_even_numbers.js
const numbers = [10, 18, 17, 11, 7, 30, 85, 37, 24, 29, 49];
const evenNumbers = [];
for (const number of numbers) {
if (number % 2 === 0) {
evenNumbers.push(number);
}
}
console.log("Even numbers:", evenNumbers);
2
3
4
5
6
7
8
9
10
11
# Longest word
Met deze applicatie woeken we het langste woord in een string, bijv. Full Stack JavaScript Development
is Development
het langste woord.
Stappenplan:
- Maak een bestand
longest_word.js
aan in de reeds aangemaakt folderweek-2
. - Schrijf een functie genaamd
searchLongestWord
dat:- 1 argument bevat: de tekst waarin we het langste woord zoeken
- geeft het langste woord terug
./artevelde/pgm-code/pgm-1/week-2/longest_word.js
function searchLongestWord(text, character) {
const words = text.split(" ");
let longestWord = "";
for (const word of words) {
if (longestWord.length < word.length) {
longestWord = word;
}
}
return longestWord;
}
console.log(searchLongestWord("Full Stack JavaScript Development"));
2
3
4
5
6
7
8
9
10
11
12
# Controleren op W
Maak een bestand check_for_w.js
aan in de reeds aangemaakt folder week-2
.
Controleer of een string de letter “w” bevat. Druk “ja” af als dat zo is en “nee” als dat niet zo is.
Gebruik een for...of
loop om elk karakter in de string te controleren.
const str2 = "don’t know why";
// Example output:
// "ja"
2
3
./artevelde/pgm-code/pgm-1/week-2/check_for_w.js
// optie 1 (rechtstreeks for ... of op string)
const str1 = "don’t know why";
let hasW = false;
for (const char of str1) {
if (char.toLowerCase() === "w") {
hasW = true;
}
}
console.log(hasW ? "Ja" : "Nee");
// optie 2 (met split)
const str2 = "don’t know why";
const words = str2.split("");
let hasW = false;
for (const char of words) {
if (char.toLowerCase() === "w") {
hasW = true;
}
}
console.log(hasW ? "Ja" : "Nee");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Count words in a string
Tel het aantal woorden in een string.
- Maak een bestand
count_words_in_string.js
aan in de reeds aangemaakt folderweek-2
. - Maak een variable
text
met een zelfgekozen zin - Verwijder alle punctuation via
text.replace(/[.,\/#!$%\^&\*;:{}=\-_~()]/g,"");
. - Log het aantal woorden in de zin naar de console.
./artevelde/pgm-code/pgm-1/week-2/count_words_in_string.js
let text =
"3 May. Bistritz.—Left Munich at 8:35 P. M., on 1st May, arriving at Vienna early next morning; should have arrived at 6:46, but train was an hour late. Buda-Pesth seems a wonderful place, from the glimpse which I got of it from the train and the little I could walk through the streets. I feared to go very far from the station, as we had arrived late and would start as near the correct time as possible. The impression I had was that we were leaving the West and entering the East; the most western of splendid bridges over the Danube, which is here of noble width and depth, took us among the traditions of Turkish rule. We left in pretty good time, and came after nightfall to Klausenburgh. Here I stopped for the night at the Hotel Royale. I had for dinner, or rather supper, a chicken done up some way with red pepper, which was very good but thirsty. (Mem., get recipe for Mina.) I asked the waiter, and he said it was called “paprika hendl,” and that, as it was a national dish, I should be able to get it anywhere along the Carpathians. I found my smattering of German very useful here; indeed, I don’t know how I should be able to get on without it. Having had some time at my disposal when in London, I had visited the British Museum, and made search among the books and maps in the library regarding Transylvania; it had struck me that some foreknowledge of the country could hardly fail to have some importance in dealing with a nobleman of that country. ...";
// Remove all of the punctuation (e.g. ".", ",", "!", "?") to tidy up the results
text = text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
const words = text.split(" ");
console.log(words.length);
2
3
4
5
6
7
8
# Count unique words in a string
Tel het aantal unieke woorden in een string.
- Maak een bestand
count_words_in_unique_string.js
aan in de reeds aangemaakt folderweek-2
. - Maak een variable
text
met een zelfgekozen zin - Verwijder alle punctuation via
text.replace(/[.,\/#!$%\^&\*;:{}=\-_~()]/g,"");
. - Overloop de woorden en tel het aantal unieke woorden. Log dit naar de console.
./artevelde/pgm-code/pgm-1/week-2/count_unique_words_in_string.js
const text =
"3 May. Bistritz.—Left Munich at 8:35 P. M., on 1st May, arriving at Vienna early next morning; should have arrived at 6:46, but train was an hour late. Buda-Pesth seems a wonderful place, from the glimpse which I got of it from the train and the little I could walk through the streets. I feared to go very far from the station, as we had arrived late and would start as near the correct time as possible. The impression I had was that we were leaving the West and entering the East; the most western of splendid bridges over the Danube, which is here of noble width and depth, took us among the traditions of Turkish rule. We left in pretty good time, and came after nightfall to Klausenburgh. Here I stopped for the night at the Hotel Royale. I had for dinner, or rather supper, a chicken done up some way with red pepper, which was very good but thirsty. (Mem., get recipe for Mina.) I asked the waiter, and he said it was called “paprika hendl,” and that, as it was a national dish, I should be able to get it anywhere along the Carpathians. I found my smattering of German very useful here; indeed, I don’t know how I should be able to get on without it. Having had some time at my disposal when in London, I had visited the British Museum, and made search among the books and maps in the library regarding Transylvania; it had struck me that some foreknowledge of the country could hardly fail to have some importance in dealing with a nobleman of that country. ...";
// Remove all of the punctuation (e.g. ".", ",", "!", "?") to tidy up the results
text = text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
// Split on space character in order to generate an array of words
const words = text.split(" ");
const uniqueWords = [];
for (const word of words) {
// check if the word is not already in the array
if (!uniqueWords.includes(word)) {
uniqueWords.push(word);
}
}
console.log(`${uniqueWords.length} unieke woorden`);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Som van arrays
Maak een bestand sum_arrays.js
aan in de reeds aangemaakt folder week-2
.
Maak de som van twee matrices, waarbij je eerst de som maakt van al hun elementen. Elke array bevat alleen gehele getallen. De output is ook een geheel getal.
const arrayOne = [3, 5, 22, 5, 7, 2, 45, 75, 89, 21, 2]; // --> 276
const arrayTwo = [9, 2, 42, 55, 71, 22, 4, 5, 90, 25, 26]; // --> 351
// Example output:
// 276 + 351 = 627
2
3
4
./artevelde/pgm-code/pgm-1/week-2/sum_arrays.js
const arrayOne = [3, 5, 22, 5, 7, 2, 45, 75, 89, 21, 2];
const arrayTwo = [9, 2, 42, 55, 71, 22, 4, 5, 90, 25, 26];
let sumOne = 0;
for (const number of arrayOne) {
sumOne += number;
}
let sumTwo = 0;
for (const number of arrayTwo) {
sumTwo += number;
}
console.log(`${sumOne} + ${sumTwo} = ${sumOne + sumTwo}`);
2
3
4
5
6
7
8
9
10
11
12
13
14
# Say Blah function
Maak een bestand function_say_blah.js
aan in de reeds aangemaakt folder week-2
. In deze functie loggen we de volgende conversatie naar het output scherm:
- Schrijf een functie genaamd
sayBlah
dat onderstaande conversatie naar de console logt. - Roep deze functie 1 keer aan
Zack: Check it out, all about planets this month.
Leonard: That’s an atom.
Zack: Agree to disagree. That’s what I love about science, there’s no one right answer.
Leonard: So, you and Zack again, huh?
Penny: Yeah, yeah, me and Zack again.
2
3
4
5
6
7
8
9
Voorbeeld:
sayBlah(); // …
./artevelde/pgm-code/pgm-1/week-2/function_say_blah.js
function sayBlah() {
console.log(`
Zack: Check it out, all about planets this month.
Leonard: That’s an atom.
Zack: Agree to disagree. That’s what I love about science, there’s no one right answer.
Leonard: So, you and Zack again, huh?
Penny: Yeah, yeah, me and Zack again.
`);
}
sayBlah();
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Hello World function
Maak een bestand function_hello.js
aan in de reeds aangemaakt folder week-2
.
- Schrijf een functie genaamd
sayHello
dat:- gebruik maakt van
return
om de boodschap “Hello World” te retourneren
- gebruik maakt van
- Roep deze functie 2 keer aan
Voorbeeld:
console.log(sayHello()); // Hello World
./artevelde/pgm-code/pgm-1/week-2/function_hello.js
function sayHello() {
return "Hello world";
}
console.log(sayHello());
console.log(sayHello());
2
3
4
5
6
# Random number function
Maak een bestand function_random_number.js
aan in de reeds aangemaakt folder week-2
.
- Schrijf een functie genaamd
getRandomNumber
dat:- gebruik maakt van
return
om de een random gegenereerd getal te retourneren
- gebruik maakt van
- Roep deze functie 2 keer aan
./artevelde/pgm-code/pgm-1/week-2/function_random_number.js
function getRandomNumber() {
return Math.random(); // random getal tussen 0 en 0.99
}
console.log(getRandomNumber());
2
3
4
5
# Personal Message function
Maak een bestand function_message.js
aan in de reeds aangemaakt folder week-2
.
- Schrijf een functie genaamd
getPersonalMessage
dat:- 1 argument bevat: de naam van de gebruiker
- gebruik maakt van
return
om de boodschap bijv.Greetings drdynscript you will be a great developer :)
te retourneren
- Roep deze functie 2 keer aan, steeds met een andere waarde voor het argument
Mogelijke oplossing:Voorbeeld:
getPersonalMessage("drdynscript"); // Greetings drdynscript you will be a great developer :)
1
./artevelde/pgm-code/pgm-1/week-2/function_message.js
function getPersonalMessage(name) {
return `Greeting ${name} you will be a great developer :)`;
}
console.log(getPersonalMessage("Philippe"));
console.log(getPersonalMessage("Mark"));
2
3
4
5
6
# Random number function with parameters
Maak een bestand function_random_number_with_parameters.js
aan in de reeds aangemaakt folder week-2
.
- Schrijf een functie genaamd
generateRandomNumber
dat:- 1 argument bevat: ondergrens van het te genereren random getal
- 1 argument bevat: bovengrens van het te genereren random getal
- gebruik maakt van
return
om de een random gegenereerd getal te retourneren op basis van de argumenten
- Roep deze functie 2 keer aan, steeds met een andere waarde voor de argumenten
Mogelijke oplossing:Voorbeeld:
generateRandomNumber(20, 30); // 26 generateRandomNumber(5, 20); // 16
1
2
./artevelde/pgm-code/pgm-1/week-2/function_random_number_with_parameters.js
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(generateRandomNumber(10, 20));
console.log(generateRandomNumber(22, 345));
2
3
4
5
6
# Function exploration
In deze applicatie leer basis functies te omschrijven.
Maak een bestand function_exploration.js
aan in de reeds aangemaakt folder week-2
.
Definieer de functie checkAge()
zoals:
function checkAge(age) {
if (age > 28) {
return true;
} else {
console.log("Did your parents allow you?");
}
}
2
3
4
5
6
7
- Spreek deze functie aan
- Werkt deze functie nog als we het
else
statement verwijderen en de inhoud ervan na hetif
statement plaatsen? - Herschrijf de functie door
if…else
te vervangen door een ternary operator - Definieer een nieuwe functie
min(a, b)
die de kleinste waarde uit twee waarden teruggeeft(=retourneert). Roep deze functie een paar keer aan. - Definieer een nieuwe functie
pow(x, n)
die het getalx
tot de machtn
verheft en deze uitkomst retourneert. Roep deze functie een paar keer aan.
# Convert Fahrenheit to Celsius
Met deze applicatie kunnen we temperaturen uitgedrukt in Fahrenheit converteren naar temperaturen uitgedrukt in Celsius.
- Maak een bestand
fahrenheit_to_celsius.js
aan in de reeds aangemaakt folderweek-2
. - Schrijf een functie genaamd
convertFahrenheitToCelsius
dat:- 1 argument bevat: de temperatuur uitgedrukt in Fahrenheit
- converteer de temperatuur van Fahrenheit (°F) naar Celsius (°C) volgens de formule
Celsius = (fahrenheit - 32) / 1.8
- maak gebruik van
return
om het aantal graden Celsius te retourneren
- schrijf de geretourneerde waarde naar de console zoals: “Temperature of 71°F equals to 21.6°C!”
- Roep deze functie 2 keer aan, steeds met een andere waarde voor het argument
Mogelijke oplossing:Voorbeeld resultaat
Temperature of 71°F equals to 21.6°C! Temperature of 0°F equals to -17.8°C!
./artevelde/pgm-code/pgm-1/week-2/fahrenheit_to_celsius.js
function convertFahrenheitToCelsius(fahrenheit) {
const celsius = (fahrenheit - 32) / 1.8;
return celsius;
}
/*
* Define a function showMessage with no parameters
* the functions will log the conversion as a string
*/
function showMessage() {
let message = `Temperature of ${fahrenheit}°F equals to ${celsius.toFixed(1)}°C!`;
console.log(message);
}
let fahrenheit = 71; // Value 71 as fahrenheit
let celsius = convertFahrenheitToCelsius(fahrenheit); // Call the function convertFahrenheitToCelsius with argument fahrenheit in order to convert it to Celsius
showMessage(); // Show the message to the console
fahrenheit = 56; // Value 56 as fahrenheit
celsius = convertFahrenheitToCelsius(fahrenheit); // Call the function convertFahrenheitToCelsius with argument fahrenheit in order to convert it to Celsius
showMessage(); // Show the message to the console
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Count unique words in a string (function)
Tel het aantal woorden in een string. Ditmaal gaan we gebruik maken van een functie om het meerdere keren te kunnen gebruiken.
- Maak een bestand
count_unique_words_in_string_function.js
aan in de reeds aangemaakt folderweek-2
. - Schrijf een functie genaamd
calculateUniqueAmountOfWords
dat:- 1 argument bevat: de string waarvan we de woorden willen tellen
- verwijder alle punctuation via
mijnstring.replace(/[.,\/#!$%\^&\*;:{}=\-_~()]/g,"");
,mijnstring
is de naam van de variabele (kan ook een andere naam zijn) - de functie geeft het aantal woorden terug.
- Roep de functie aan en log het resultaat van deze aanroep naar de console.
./artevelde/pgm-code/pgm-1/week-2/count_unique_words_in_string_function.js
const longText =
"3 May. Bistritz.—Left Munich at 8:35 P. M., on 1st May, arriving at Vienna early next morning; should have arrived at 6:46, but train was an hour late. Buda-Pesth seems a wonderful place, from the glimpse which I got of it from the train and the little I could walk through the streets. I feared to go very far from the station, as we had arrived late and would start as near the correct time as possible. The impression I had was that we were leaving the West and entering the East; the most western of splendid bridges over the Danube, which is here of noble width and depth, took us among the traditions of Turkish rule. We left in pretty good time, and came after nightfall to Klausenburgh. Here I stopped for the night at the Hotel Royale. I had for dinner, or rather supper, a chicken done up some way with red pepper, which was very good but thirsty. (Mem., get recipe for Mina.) I asked the waiter, and he said it was called “paprika hendl,” and that, as it was a national dish, I should be able to get it anywhere along the Carpathians. I found my smattering of German very useful here; indeed, I don’t know how I should be able to get on without it. Having had some time at my disposal when in London, I had visited the British Museum, and made search among the books and maps in the library regarding Transylvania; it had struck me that some foreknowledge of the country could hardly fail to have some importance in dealing with a nobleman of that country. ...";
// Find unique words - uitbreiding
function calculateAmountOfUniqueWords(text) {
// Remove all of the punctuation (e.g. ".", ",", "!", "?") to tidy up the results
text = text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
// Split on space character in order to generate an array of words
const words = text.split(" ");
const uniqueWords = [];
for (const word of words) {
if (!uniqueWords.includes(word)) {
uniqueWords.push(word);
}
}
return uniqueWords.length;
}
console.log(`There are ${calculateAmountOfUniqueWords(longText)} unique words in the Dracula text!`);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20