Skip to content
This repository was archived by the owner on Jan 3, 2023. It is now read-only.
Open
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
118 changes: 118 additions & 0 deletions CodeWars/allExercises.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*********************************************
* CodeWars homeworks
* https://www.codewars.com/collections/cyf-js-2-week-3
************************************************** */




// 1 *********************************
//Job Matching #2
function match(job, candidates) {
// look at the candidate desiresEquity, if it's true =>
//job equityMax has to be >0 &
// candidate currentLocation + desiredLocations have to include some job locationlocation
// else => just look at the locations
return candidates.filter(candidate =>{
if(candidate.desiresEquity){
console.log(job['equityMax'] > 0 && isIncludeLocation(candidate['currentLocation'],candidate['desiredLocations'],job['locations']),"WILLRETURN")
return job['equityMax'] > 0 && isIncludeLocation(candidate['currentLocation'],candidate['desiredLocations'],job['locations'])
} else {
return isIncludeLocation(candidate['currentLocation'],candidate['desiredLocations'],job['locations']);
}
});

}
//this func will look at the locations
function isIncludeLocation (currLoc,desireLoc,jobLocation){
const allLoc= desireLoc;
allLoc.push(currLoc);//current loc is String so put inside the array
return allLoc.some(elem=>{
return jobLocation.includes(elem);
});
}


// 2 *********************************
//Split The Bill
function splitTheBill(obj) {
let counter=0;
let totalBill=0;
for(key in obj){//find avarage
counter++;
totalBill +=obj[key];
}
const avarageBill = totalBill/counter;
for(key in obj){//find result and put inside in the object
obj[key] = Number((Math.round((obj[key] -avarageBill) * 100) / 100).toFixed(2));
}
return obj;

}



// 3 *********************************
//Convert the score
function scoreboard(str) {
const score ={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9, nil:0}
const scoreArr=[];
for(key in score){
if(str.indexOf(key)!==-1){
scoreArr.push(score[key]);
scoreArr.push(str.indexOf(key));
}
}//we took [1(score),3(index),nil(score),8] OR=> [4(score),8]==if score is same
if(scoreArr.length === 2){// score same return [2,2]
return [scoreArr[0],scoreArr[0]];
} else if(scoreArr[1] < scoreArr[3]){ return [scoreArr[0],scoreArr[2]]; }
// look at the score index, return the correct order
else {return [scoreArr[2],scoreArr[0]];}
}


// 4 *********************************
//Functional Addition
function add(n) {
return function(num){
return num + n
};//declare new fucntion
}



// 5 *********************************
//Scrabblemania
function wordscore(word) {
const letterPoints ={"a" : 1, "b" : 3,"c" : 3,"d" : 2, "e" : 1, "f" : 4,"g" : 2,"h" : 4,"i" : 1,"j" : 8,"k" : 5,"l" : 1,"m" : 3,"n" : 1,"o" : 1,"p" : 3,"q" : 10,"r" : 1,"s" : 1,"t" : 1,"u" : 1,"v" : 4, "w" : 4,"x" : 8,"y" : 4,"z" : 10}
//find total point of word(letter-by-letter)
//total*length
//if length 7 add 50
let total = 0;
for(let i = 0; i < word.length; i ++){
total += letterPoints[word.charAt(i)];

}
total *= word.length;
if(word.length === 7){
return total + 50;
} else{
return total;
}
}



// 6 *********************************
//Who is the killer?
function killer(suspectInfo, dead) {
//LOOK AT ALL KEYS,
//IF ONE OF KEY HAS EVERY DEAD ELEMENT RETURN KEY
for(personSuspect in suspectInfo){
if(
dead.every(person=> suspectInfo[personSuspect].includes(person))
) //if condition end
//if all dead person inside one of suspectPerson return True
{return personSuspect; }
}
}
12 changes: 12 additions & 0 deletions InClass/Callbacks/exercise-1/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,15 @@ Update your code to make the colour change every 5 seconds to something differen
Prefer to work on a codepen? https://codepen.io/makanti/pen/abOreLg
================
*/

setTimeout(()=>{
document.body.style.backgroundColor = 'purple'
},2000);


const myColor=['red','yellow','green','orange'];
let colorIndex = 0;
setInterval(()=>{
colorIndex = (colorIndex + 1) % myColor.length;// colorindex will be next color but always will be between 0 - myColor length
document.body.style.backgroundColor = myColor[colorIndex];
},5000)
85 changes: 81 additions & 4 deletions InClass/Callbacks/exercise-2/exercise.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*
================
Exercise 2
----------
Expand All @@ -9,19 +9,60 @@ Create a function called "showMovies" that
- iterates through the "movies" array and
- for each movie, it creates a <p> element with the movie title and director and append it to the #all-movies div.
- it sets the innerText of the #movies-number element to the total number of the movies in the array "movies"
*/
// function showMovies(movies) {
// const allMovies = document.querySelector('#all-movies');
// movies.forEach(movie => {
// const p = document.createElement('p');
// p.innerText = `${movie.title} by ${movie.director}`;
// allMovies.appendChild(p);
// });
// const movieNumber = document.querySelector('#movies-number');
// movieNumber.innerText = movies.length;
// }

/*
Task 2
Amend your function above to only show movies after 1 second. Remember to use setTimeout to achieve that
Create a new function called "addMovie"
- it receives a movie object as an argument - your can create a new object for your favorite movie following using the "myMovies" objects as a guide
- it adds the new movie to the list of movies after 2 seconds. Remember to setTimeout to achieve that
Call addMovies to add the new movie to the list and then showMovies to see the movies added on the screen.
How many movies can you see on your page?
*/
function addMovie(obj,callBack){
console.log('waiting 2 secs FOR ADDING movies<<<<<')
setTimeout(()=>{
movies.push(obj);// add new film object >> to movie array
callBack(movies);// show new array
},1000);
}


function showMovies(movies) {
console.log('waiting 1 sec FOR SHOWING movies<<<<<')
setTimeout(() =>{
document.querySelectorAll("#all-movies p:not(.alert)").forEach(e => e.parentNode.removeChild(e));//choose all movie in the page and delete them ****!!!! NOTE for MATT>>>> please look at END OF THE PAGE
const allMovies = document.querySelector('#all-movies');
movies.forEach(movie => {
const p = document.createElement('p');
let film = `${movie.title} by ${movie.director}`;
p.innerText = film;
allMovies.appendChild(p);
});

const movieNumber = document.querySelector('#movies-number');
movieNumber.innerText = movies.length;
},500);
}


/*
Task 3
Can you make sure the new movie you just added is showing on the screen?
TIP: use callbacks

*/
/*
Task 4 - **Extra**
Create a form anywhere on your page. The form should have
- 4 input text fields, one for each property of your movie object
Expand All @@ -34,6 +75,18 @@ TIP: Use the functions you created on tasks 1-3
Prefer to work on a codepen? https://codepen.io/makanti/pen/MWwMgmW?editors
================
*/
const submit = document.getElementById('submit');
submit.addEventListener('click',()=>{
const newFilm ={
title: document.getElementById('title').value,
director : document.getElementById('director').value,
type : document.getElementById('type').value,
haveWatched : document.getElementById('haveWatched').value
};
addMovie(newFilm,showMovies);
})


const movies = [
{
title: "Color Out of Space",
Expand Down Expand Up @@ -61,8 +114,32 @@ const movies = [
},
];

// create showMovies function

showMovies(movies);
// create a new movie object for your favorite movie
const newmovie ={
title: "CYF",
director: "Richard Stanley",
type: "TEC",
haveWatched: true,
}
addMovie(newmovie,showMovies);



/**
*
* function isInHTML(film){
const allP =Array.from(document.querySelectorAll("#all-movies p:not(.alert)"))
console.log(allP);
return allP.some(p =>{
console.log(p.innerText,'<<<<<<<<<<<<<<<<PPPPP')
return p.innerText === film;
});
}

MATT in this function I tried to check HTML, if the film is already on the page, I don't need to add.. but i couldn't manage it. So I choose the easy way > when you call "showMovies" function, it will clear all old films and creating again..


// create addMovies function
my main goal was to make all the changes to the object. then it was just changing the relevant places on the web page. otherwise, every function will have to make changes on the web page and I will be more likely to make mistakes. or webpage will download all data again
*/
19 changes: 19 additions & 0 deletions InClass/Callbacks/exercise-2/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,25 @@ <h1>My movies</h1>
<div id="all-movies">
<p class="alert alert-info">Number of movies: <span id="movies-number"></span></p>
</div>

<form>
<fieldset>
<legend>Add New Movie</legend>
<label for="title">Title of the Film :</label><br>
<input type="text" id="title" name="title" placeholder="The Lord of The Ring"><br>
<label for="director">Director :</label><br>
<input type="text" id="director" name="director" placeholder="Peter Jackson"><br>
<label for="type">Type :</label><br>
<input type="text" id="type" name="type" placeholder="Adventure"><br>
<label for="type">Did you watch ?</label><br>
<select id="haveWatched" >
<option value="true">I watched</option>
<option value="false">I didn't watch</option>
</select>
</fieldset>
</form>
<br>
<input type="submit" id="submit" value="Submit">
</div>
<script src="exercise.js"></script>
</body>
Expand Down
27 changes: 24 additions & 3 deletions InClass/DOM-practice/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ console.log("Testing JS file loaded!")
// Task 1

// Without changing any of the HTML or CSS, update the <section> tags so that they have white backgrounds.

const sections =Array.from(document.querySelectorAll('section'));
sections.forEach(section =>{
section.style.backgroundColor = 'white';
})



Expand All @@ -14,12 +17,30 @@ console.log("Testing JS file loaded!")
// Without changing any of the HTML or CSS, update the images on the page so that they are all centered.

// Hint: look at the CSS to see if there are any classes already written which you can use.


// .content-title
const images = document.querySelectorAll('img');
// console.log( images,'<<<<<<');
images.forEach(img =>{
img.classList.add('content-title');
});




// Task 3

// Google the date of birth and death of each of the people on the page. Without changing any of the HTML or CSS, add this in a paragraph to the end of their <section>.
const p1 = `Born: 9 December 1906
Died: 1 January 1992`;
const p2 = `Born: 26 August 1918
Died: 24 February 2020`;
const p3 = `Born: 10 December 1815
Died: 27 November 1852`;
const bornAndDiedDates= [p1,p2,p3];

sections.forEach((eachSection,index)=>{
//for every section > create p, put dates orderly
const p = document.createElement('p');
p.innerText =bornAndDiedDates[index];
eachSection.appendChild(p);
});
1 change: 1 addition & 0 deletions extra/1-quote-generator-revisited/task.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Add auto-play to your quote generator
**ADDED INSIDE QUOTE GENERATOR**

For this task you will return to your quote generator and improve it with "auto-generate" functionality:

Expand Down
2 changes: 1 addition & 1 deletion extra/2-slideshow-extra/task.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Extra Task for Slideshow

**ADDED INSIDE SLIDE SHOW**
## Optional: Add UI for delay time

Add UI so that the user can specify how long to wait between images.
Expand Down
35 changes: 33 additions & 2 deletions mandatory/1-alarmclock/alarmclock.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
function setAlarm() {}
function setAlarm() {
const h1 = document.getElementById('timeRemaining');
let input = document.getElementById('alarmSet').value;
let intervalID= setInterval(() => {
const hour =Math.floor(input/60).toString().padStart(2, "0");
//FOR MORE INFO ABOUT padStart() >>> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't know padStart() exists :) I am learning new things from your code as always. Great job

const sec = (input % 60).toString().padStart(2, "0");
h1.innerText =`Time Remaining: ${hour}:${sec}`;
if(input === 0) {
clearInterval(intervalID);//stop timer
doFlash();///EXTRA
playAlarm();
} else {
input--;
}
}, 1000);
}
///EXTRA
function doFlash(){
const colors =['red','orange','green'];
let index =0;
//if stop alarm clicked stop flash else doflash
const flashID= setInterval(() => {
index++;
document.body.style.backgroundColor = colors[index%colors.length];
}, 100);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[index%colors.length], this is smart

document.getElementById("stop").addEventListener("click", () => {
clearInterval(flashID);
document.body.style.backgroundColor = 'white';

});
}

// DO NOT EDIT BELOW HERE

var audio = new Audio("alarmsound.mp3");
Expand All @@ -22,4 +53,4 @@ function pauseAlarm() {
audio.pause();
}

window.onload = setup;
window.onload = setup;
Loading