Skip to content

Commit

Permalink
Merge pull request #6 from MADAkwasi/closures
Browse files Browse the repository at this point in the history
feat: add closures
  • Loading branch information
MADAkwasi authored Nov 25, 2024
2 parents 243914a + 9122bca commit 9a943e5
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
22 changes: 22 additions & 0 deletions week_2/closures/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script defer src="script.js"></script>
<title>Document</title>
</head>
<body
style="
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
gap: 10px;
"
>
<h1></h1>
<button>Click</button>
</body>
</html>
84 changes: 84 additions & 0 deletions week_2/closures/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"use strict";
const btn = document.querySelector("button");
const text = document.querySelector("h1");

/// call(), apply() and bind()
const person = {
name: "Mike",
age: 50,
greet(hobby) {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old and hobby is ${hobby}`
);
},
};

const worker = {
name: "Bob",
age: 4,
};

const aboutWorker = person.greet.bind(worker, "playing keyboard");
aboutWorker();

person.greet.apply(worker, ["playing keyboard"]);
person.greet.call(worker, "playing keyboard");

///Event handlers and this

function handleClick() {
console.log(this.textContent);
}

const clickHandler = () => {
console.log(this.id);
};

btn.addEventListener("click", handleClick);

btn.addEventListener("click", clickHandler);

///Private Variables

function createCounter() {
let count = 0;

return {
increment: function () {
count++;
console.log(this.count);
},
getCount: function () {
return count;
},
};
}

const counter = createCounter();

counter.increment();
counter.increment();
counter.increment();
counter.increment();
console.log(counter.getCount());

///Reusable Components

function createTimer(duration, elementId) {
const intervalId = setInterval(() => {
elementId.textContent = duration;
duration--;

if (duration < 0) {
clearInterval(intervalId);
elementId.textContent = 0;
console.log("Timer expired");
}
}, 1000);

return { startTime: duration, elementId };
}

const remainingTime = createTimer(5, text);

console.log(remainingTime);

0 comments on commit 9a943e5

Please sign in to comment.