Created
July 18, 2022 14:08
-
-
Save djsd123/dd140f62aaa0c609f050e00ebf919e11 to your computer and use it in GitHub Desktop.
A Function in Typescript/Javascript that can only be called/executed once
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
/* | |
I wanted a function that would only work once where all subsequent calls would result in a noop | |
I stumbled upon this Stackoverflow question: https://stackoverflow.com/questions/12713564/function-in-javascript-that-can-be-called-only-once | |
However, I found some of the answers difficult to implement in Typescript but on the bright side. I learnt a little about closures. | |
I added my simple workaround here: https://stackoverflow.com/a/72992927/2719085 and below. | |
*/ | |
let printName = (name: string) => { | |
console.log(name) | |
printName = () => {} | |
} | |
printName('Sophia') // Sophia | |
printName('Nico') // Nothing Happens | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment