Skip to content

Commit

Permalink
Learned about closures with asynchronous code, partial application an…
Browse files Browse the repository at this point in the history
…d currying and how to preserve states
  • Loading branch information
sohail019 committed Jul 31, 2024
1 parent 359e07b commit ea17a7f
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Closure with Asynchronous Code

function fetchData(url){

fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok`)
}
return response.json()
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log(
"There has been a problem with your fetch operation:",
error
);
})
}

fetchData("https://api.github.com/users/sohail019");
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Partial applications and currying

function multiply(x){
return function(y){
return x * y
}
}


const double = multiply(2)
console.log(double(5)) // 10

const triple = multiply(3)
console.log(triple(5)) // 15

// Here, multiply is curried function that returns a closure, allowing for partial application of the multiple operation.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Preserving States

function makeToggle(){
let isOn = false

return function(){

isOn = !isOn
return isOn
}
}

const toggle = makeToggle();

console.log(toggle()) // true
console.log(toggle()) // false
console.log(toggle()) // true

// The makeToggle function creates a closure that preserves the isOn state across multiple calls, effectively toggling the state each time it is invoked.

0 comments on commit ea17a7f

Please sign in to comment.