Created
August 3, 2021 13:40
-
-
Save kahunacohen/057743cf75321b39728a249b55f37799 to your computer and use it in GitHub Desktop.
Shows how ES "classes" are really just functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Stripe { | |
constructor(baseUrl, token) { | |
this.baseUrl = baseUrl; | |
this.token = token; | |
this.expensiveResult = null; | |
} | |
getCustomers() { | |
console.log(`Getting ${this.baseUrl}/customers with token ${this.token}`); | |
} | |
someExpensiveOperation() { | |
return new Promise((resolve, _) => { | |
if (this.expensiveResult) { | |
resolve(this.expensiveResult); | |
} else { | |
setTimeout(() => { | |
this.expensiveResult = 10; | |
resolve(10); | |
}, 1000); | |
} | |
}); | |
} | |
} | |
console.log("Class based:"); | |
const stripe = new Stripe("https://api.stripe.com/v1", "xyz"); | |
stripe.getCustomers("/customers"); | |
stripe.someExpensiveOperation().then(x => console.log(x)); | |
stripe.someExpensiveOperation().then(x => console.log(x)); | |
stripe.someExpensiveOperation().then(x => console.log(x)); | |
function Stripe2(baseUrl, token) { | |
let expensiveResult = null; | |
return { | |
getCustomers: () => console.log(`Getting ${baseUrl}/customers with token ${token}`), | |
someExpensiveOperation: () => { | |
return new Promise((resolve, _) => { | |
if (expensiveResult) { | |
resolve(expensiveResult); | |
} else { | |
setTimeout(() => { | |
expensiveResult = 10; | |
resolve(10); | |
}, 1000); | |
} | |
}); | |
} | |
} | |
} | |
console.log("Function based:"); | |
const {getCustomers, someExpensiveOperation} = Stripe2("https://api.stripe.com/v1", "xyz"); | |
getCustomers(); | |
someExpensiveOperation().then(x => console.log(x)); | |
someExpensiveOperation().then(x => console.log(x)); | |
someExpensiveOperation().then(x => console.log(x)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment