Last active
November 10, 2016 17:18
-
-
Save komplexb/c4ad683659f40c1181a4266961d93a6a to your computer and use it in GitHub Desktop.
2. functional js: hiding state in a closure via https://youtu.be/kA4-b7hvWhg
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
// run: https://repl.it/EU15/3 | |
function writeComment(count, author, text) { | |
if(count > 3) { | |
throw new Error(author + 'executed too many actions!!'); | |
} | |
console.log(author, text); // saveComment(author, text); | |
return count + 1; | |
} | |
// add a function with two closures | |
// one risk, can't easily cache, i don't know what that means... yet | |
function makeWriteCommentFunction(author) { | |
var counter = 0; | |
return function(text) { | |
counter = writeComment(counter, author, text); | |
} | |
} | |
var currentUserWritesComment = makeWriteCommentFunction('byron'); | |
currentUserWritesComment('Check out my stuff'); | |
currentUserWritesComment('Check out my stuff'); | |
currentUserWritesComment('Check out my stuff'); | |
currentUserWritesComment('Check out my stuff'); | |
currentUserWritesComment('Check out my stuff'); |
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
function writeComment(count, author, text) { | |
if(count > 3) { | |
throw new Error(author + 'executed too many actions!!'); | |
} | |
console.log(author, text); // saveComment(author, text); | |
return count + 1; | |
} | |
var counter = 0; | |
counter = writeComment(counter, 'bbuckley', 'Check this out'); | |
counter = writeComment(counter, 'bbuckley', 'Check this out'); | |
counter = writeComment(counter, 'bbuckley', 'Check this out'); | |
counter = writeComment(counter, 'bbuckley', 'Check this out'); | |
counter = writeComment(counter, 'bbuckley', 'Check this out'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment