Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Js-Week-1 prep-exercises #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"githubPullRequests.ignoredPullRequestBranches": ["main"]
}
14 changes: 10 additions & 4 deletions Week1/practice-exercises/1-remove-the-comma.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
/**
* We want to remove the comma's in the given string (myString), replace them with a space and log it to the console.
*
* The end result should be:
*
* The end result should be:
* hello this is a difficult to read sentence
*/

let myString = 'hello,this,is,a,difficult,to,read,sentence';


// solution 1
myString = myString.replaceAll(',', ' ');
// solution 2
// myString = myString.split(',').join(' ');

/* --- Code that will test your solution, do NOT change. Write above this line --- */

console.assert(myString === 'hello this is a difficult to read sentence', 'There is something wrong with your solution');
console.assert(
myString === 'hello this is a difficult to read sentence',
'There is something wrong with your solution'
);
6 changes: 5 additions & 1 deletion Week1/practice-exercises/2-even-odd-reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,8 @@
* If it's odd, log to the console The number [PUT_NUMBER_HERE] is odd!.
* If it's even, log to the console The number [PUT_NUMBER_HERE] is even!.
*/

for (let number = 0; number <= 20; number++) {
number % 2 == 0
? console.log(`The number ${number} is Even!`)
: console.log(`The number ${number} is odd!`);
}
26 changes: 22 additions & 4 deletions Week1/prep-exercises/1-traffic-light/traffic-light-1.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,34 @@
"use strict";
'use strict';
/**
* The `state` property says what the traffic light's state (i.e. colour) is at
* that moment.
*/
const trafficLight = {
state: "green",
let trafficLight = {
state: 'green',
};

let rotations = 0;
while (rotations < 2) {
const currentState = trafficLight.state;
console.log("The traffic light is on", currentState);
console.log('The traffic light is on', currentState);

//single line solution
currentState == 'green'
? (trafficLight.state = 'orange')
: currentState == 'orange'
? (trafficLight.state = 'red')
: `(${(trafficLight.state = 'green')} ${rotations++})`;

/*
if(currentState == "green"){
trafficLight.state = "orange";
} else if(currentState == "orange"){
trafficLight.state = "red";
}else{
rotations++;
trafficLight.state = "green";
}
*/

// TODO
// if the color is green, turn it orange
Expand Down
19 changes: 16 additions & 3 deletions Week1/prep-exercises/1-traffic-light/traffic-light-2.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
"use strict";
'use strict';
/**
* The `possibleStates` property define the states (in this case: colours)
* in which the traffic light can be.
* The `stateIndex` property indicates which of the possible states is current.
*/
const trafficLight = {
possibleStates: ["green", "orange", "red"],
possibleStates: ['green', 'orange', 'red'],
stateIndex: 0,
};

let cycle = 0;
while (cycle < 2) {
const currentState = trafficLight.possibleStates[trafficLight.stateIndex];
console.log("The traffic light is on", currentState);
console.log('The traffic light is on', currentState);
// single line solution
currentState == 'green' || currentState == 'orange'
? trafficLight.stateIndex++
: `${(trafficLight.stateIndex -= 2)} ${cycle++}`;

/*
if (currentState == 'green' || currentState == 'orange') {
trafficLight.stateIndex++;
} else {
trafficLight.stateIndex -= 2;
cycle++;
}
*/

// TODO
// if the color is green, turn it orange
Expand Down
8 changes: 5 additions & 3 deletions Week2/prep-exercises/1-traffic-light/traffic-light.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
"use strict";
'use strict';
/**
* The `trafficLight` object is now no longer a global variable. Instead,
* it is defined in function `main()` and passed as a parameter to other
* functions, as and when needed.
*/

function getCurrentState(trafficLight) {
return trafficLight.possibleStates[trafficLight.stateIndex];
// TODO
// Should return the current state (i.e. colour) of the `trafficLight`
// object passed as a parameter.
}

function getNextStateIndex(trafficLight) {
return trafficLight.stateIndex == 2 ? 0 : ++trafficLight.stateIndex;
// TODO
// Return the index of the next state of the `trafficLight` such that:
// - if the color is green, it will turn to orange
Expand All @@ -33,13 +35,13 @@ function waitSync(secs) {

function main() {
const trafficLight = {
possibleStates: ["green", "orange", "red"],
possibleStates: ['green', 'orange', 'red'],
stateIndex: 0,
};

for (let cycle = 0; cycle < 6; cycle++) {
const currentState = getCurrentState(trafficLight);
console.log(cycle, "The traffic light is now", currentState);
console.log(cycle, 'The traffic light is now', currentState);

waitSync(1); // Wait a second before going to the next state
trafficLight.stateIndex = getNextStateIndex(trafficLight);
Expand Down
17 changes: 17 additions & 0 deletions Week2/prep-exercises/2-experiments/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dice experimentation</title>
</head>
<body>
<h1>Dice experimentation</h1>
<h2>Results :</h2>

<p id="1"></p>
<p id="2"></p>
<p id="3"></p>
<script src="./index.js"></script>
</body>
</html>
46 changes: 38 additions & 8 deletions Week2/prep-exercises/2-experiments/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
"use strict";
'use strict';
// new function is created for code reusable.
// This function will give you random number from 1 to 6
function rollDice(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + 1;
}

function percent(diceRolled, totalDiceRoll) {
return (diceRolled / totalDiceRoll) * 100;
}

function runExperiment(sampleSize) {
const valueCounts = [0, 0, 0, 0, 0, 0];

for (let index = sampleSize; index > 0; --index) {
let result = rollDice(1, 6);
valueCounts[result - 1] += 1;
}
// TODO
// Write a for loop that iterates `sampleSize` times (sampleSize is a number).
// In each loop iteration:
Expand All @@ -14,7 +26,14 @@ function runExperiment(sampleSize) {
// element for value 2, etc.

const results = [];

valueCounts.forEach((rolledDiceCount) => {
// console.log(percent(rolledDiceCount, sampleSize));
results.push(
` '${parseFloat(percent(rolledDiceCount, sampleSize))
.toFixed(2)
.toString()}'`
);
});
// TODO
// Write a for..of loop for the `valueCounts` array created in the previous
// loop. In each loop iteration:
Expand All @@ -31,13 +50,24 @@ function runExperiment(sampleSize) {
function main() {
const sampleSizes = [100, 1000, 1000000];

for (let index = 0; index < sampleSizes.length; index++) {
console.log(
`[ ${runExperiment(sampleSizes[index])} ] ${sampleSizes[index]}`
);

// This just extra to print the result on the webpage
document.getElementById(
(index + 1).toString()
).innerHTML = `[ ${runExperiment(sampleSizes[index])} ] ${
sampleSizes[index]
}`;
}
// TODO
// Write a for..of loop that calls the `runExperiment()` function for each
// value of the `sampleSizes` array.
// Log the results of each experiment as well as the experiment size to the
// console.
// Write a for..of loop
// that calls the `runExperiment()` function for each value of the `sampleSizes` array.
// Log the results of each experiment as well as the experiment size to the console.
// The expected output could look like this:
//

// [ '26.00', '17.00', '10.00', '19.00', '16.00', '12.00' ] 100
// [ '14.60', '17.10', '19.30', '15.50', '16.70', '16.80' ] 1000
// [ '16.71', '16.68', '16.69', '16.66', '16.67', '16.59' ] 1000000
Expand Down
39 changes: 34 additions & 5 deletions Week3/prep-exercises/1-hyf-program/1-find-mentors.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { modules, students, mentors, classes } from "./hyf.js";
import { modules, students, mentors, classes } from './hyf.js';

/**
* Tjebbe would like help to get a list of possible mentors for a module.
Expand All @@ -7,20 +7,49 @@ import { modules, students, mentors, classes } from "./hyf.js";
* It should return an array of names. So something like:
* ['John', 'Mary']
*/



const possibleMentorsForModule = (moduleName) => {
// TODO complete this function

const mentorList = [];
mentors.forEach((mentor) => {
if (mentor.canTeach.includes(moduleName)) {
mentorList.push(mentor.name);
}
});
return mentorList;
};
// You can uncomment out this line to try your function
// console.log(possibleMentorsForModule('using-apis'));
console.log(`${possibleMentorsForModule('using-apis')} can teach API module`);

/**
* Tjebbe wants to make it even easier for himself.
* Fill in this function that chooses a random mentor to teach the given module.
*
* It should return a single name.
*/

// const maxNum = 10;
// const minNum = 0;
// const randomNumber = Math.floor(Math.random() * (maxNum - minNum + 1) + minNum);
// console.log(randomNumber);

const findMentorForModule = (moduleName) => {
// TODO complete this function
const mentorList = [];
let randomNum;
mentors.forEach((mentor) => {
if (mentor.canTeach.includes(moduleName)) {
mentorList.push(mentor.name);
}
});
const maxNum = mentorList.length - 1;
const minNum = 0;
randomNum = Math.floor(Math.random() * (maxNum - minNum + 1) + minNum);
const randomMentor = mentorList[randomNum];
return randomMentor;
};
// You can uncomment out this line to try your function
// console.log(findMentorForModule('javascript'));
console.log(
`${findMentorForModule('javascript')} is going to teach Javascript`
);
69 changes: 65 additions & 4 deletions Week3/prep-exercises/1-hyf-program/2-class-list.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { modules, students, mentors, classes } from "./hyf.js";
import { modules, students, mentors, classes } from './hyf.js';

/**
* We would like to have a list of everyone that is currently participating in a class.
Expand All @@ -12,10 +12,28 @@ import { modules, students, mentors, classes } from "./hyf.js";
* [{ name: 'John', role: 'student' }, { name: 'Mary', role: 'mentor' }]
*/
const getPeopleOfClass = (className) => {
// TODO complete this function
let everyone = [];
let currentModule;

classes.forEach((eachClass) => {
if (eachClass.name == className) currentModule = eachClass.currentModule;
});

students.forEach((stud) => {
if (stud.class == className) {
everyone.push({ name: stud.name, role: 'student' });
}
});

mentors.forEach((mentor) => {
if (mentor.nowTeaching == currentModule)
everyone.push({ name: mentor.name, role: 'mentor' });
});

return everyone;
};
// You can uncomment out this line to try your function
// console.log(getPeopleOfClass('class34'));
console.log(getPeopleOfClass('class34'));

/**
* We would like to have a complete overview of the current active classes.
Expand All @@ -31,6 +49,49 @@ const getPeopleOfClass = (className) => {
*/
const getActiveClasses = () => {
// TODO complete this function

const activeClasses = classes
.map((eachClass) => {
if (eachClass.active) return eachClass.name;
})
.filter((eachClass) => eachClass !== undefined);

const activeStudent = students
.map((student) => {
if (student.graduated == false)
return { name: student.name, class: student.class, role: 'student' };
})
.filter((student) => student !== undefined);

const activeModule = classes
.filter((eachClass) => eachClass.active)
.map((eachClass) => eachClass.currentModule);

const activeMentor = mentors
.map((mentor) => {
if (activeModule.includes(mentor.nowTeaching)) {
const mentorName = mentor.name;
const className = classes
.filter((eachClass) => eachClass.currentModule == mentor.nowTeaching)
.map((eachClass) => eachClass.name)
.pop();
return { name: mentorName, class: className, role: 'mentor' };
}
})
.filter((mentor) => mentor !== undefined);

const activeClassObj = activeClasses.map((eachClass) => {
const studentList = activeStudent.filter(
(student) => student.class == eachClass
);
const mentorList = activeMentor.filter(
(mentor) => mentor.class == eachClass
);
return { [eachClass]: [...studentList, ...mentorList] };
});

return JSON.stringify(activeClassObj, null, 2);
};
// You can uncomment out this line to try your function
// console.log(getActiveClasses());
console.log('active classes:');
console.log(getActiveClasses());
Loading